1# @ohos.bluetooth.ble (Bluetooth BLE Module) 2 3<!--Kit: Connectivity Kit--> 4<!--Subsystem: Communication--> 5<!--Owner: @enjoy_sunshine--> 6<!--Designer: @chengguohong; @tangjia15--> 7<!--Tester: @wangfeng517--> 8<!--Adviser: @zhang_yixin13--> 9 10The **ble** module provides Bluetooth Low Energy (BLE) capabilities, including BLE scan, BLE advertising, and Generic Attribute Profile (GATT)-based connection and data transmission. 11 12> **NOTE** 13> - The initial APIs of this module are supported since API version 10. Newly added APIs will be marked with a superscript to indicate their earliest API version. 14> - You can use [util.generateRandomUUID](../apis-arkts/js-apis-util.md#utilgeneraterandomuuid9) to generate a UUID wherever necessary. 15 16 17 18## Modules to Import 19 20```js 21import { ble } from '@kit.ConnectivityKit'; 22``` 23 24 25## ProfileConnectionState<sup>10+</sup> 26 27type ProfileConnectionState = constant.ProfileConnectionState 28 29Defines the profile connection status of the Bluetooth device. 30 31**Atomic service API**: This API can be used in atomic services since API version 12. 32 33**System capability**: SystemCapability.Communication.Bluetooth.Core 34 35| Type | Description | 36| ------------------- | ------------------- | 37| [constant.ProfileConnectionState](js-apis-bluetooth-constant.md#profileconnectionstate) | Profile connection status of the Bluetooth device.| 38 39 40## ble.createGattServer 41 42createGattServer(): GattServer 43 44Creates a [GattServer](#gattserver) instance, which represents the server in a GATT connection. 45- You can use this instance to operate the server, for example, call [addService](#addservice) to add a server and use [notifyCharacteristicChanged](#notifycharacteristicchanged) report characteristic changes. 46 47**Atomic service API**: This API can be used in atomic services since API version 12. 48 49**System capability**: SystemCapability.Communication.Bluetooth.Core 50 51**Return value** 52 53| Type | Description | 54| ----------------------------- | ---------- | 55| [GattServer](#gattserver) | **GattServer** instance created.| 56 57**Example** 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 69Creates a [GattClientDevice] instance, which represents the client in a GATT connection. 70- You can use this instance to operate the client, for example, call [connect](#connect) to initiate a connection to the peer device and call [getServices](#getservices) to obtain all service capabilities supported by the peer device. 71- This API requires the device address of the server. You can obtain the device address of the server by calling [ble.startBLEScan](#blestartblescan) or [startScan](#startscan15) of [BleScanner](#blescanner15). Ensure that the BLE advertising of the server is enabled. 72 73**Atomic service API**: This API can be used in atomic services since API version 12. 74 75**System capability**: SystemCapability.Communication.Bluetooth.Core 76 77**Parameters** 78 79| Name | Type | Mandatory | Description | 80| -------- | ------ | ---- | ------------------------------------ | 81| deviceId | string | Yes | Address of the peer device, for example, XX:XX:XX:XX:XX:XX.| 82 83**Return value** 84 85| Type | Description | 86| ------------------------------------- | ------------------------------------ | 87| [GattClientDevice](#gattclientdevice) | **GattClientDevice** instance.| 88 89**Error codes** 90 91For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 92 93| ID| Error Message| 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**Example** 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 114Obtains the BLE devices that have been connected to the local device via GATT. 115- It is recommended that this API be used on the server. If this API is used on the client, the returned device address is empty. 116 117**Required permissions**: ohos.permission.ACCESS_BLUETOOTH 118 119**System capability**: SystemCapability.Communication.Bluetooth.Core 120 121**Return value** 122 123| Type | Description | 124| ------------------- | ------------------- | 125| Array<string> | Addresses of BLE devices that have been connected to the local device via GATT.<br>For security purposes, the device addresses obtained are virtual MAC addresses.<br>- The virtual address remains unchanged after a device is paired successfully.<br>- If a device is unpaired or Bluetooth is disabled, the virtual address will change after the device is paired again.<br>- To persistently save the addresses, call [access.addPersistentDeviceId](js-apis-bluetooth-access.md#accessaddpersistentdeviceid16).| 126 127**Error codes** 128 129For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Bluetooth Error Codes](errorcode-bluetoothManager.md). 130 131| ID| Error Message| 132| -------- | ---------------------------- | 133|201 | Permission denied. | 134|801 | Capability not supported. | 135|2900001 | Service stopped. | 136|2900003 | Bluetooth disabled. | 137|2900099 | Operation failed. | 138 139**Example** 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 155Starts BLE scanning. 156- You can obtain the scan result through the callback of [ble.on('BLEDeviceFind')](#bleonbledevicefind). Only BLE devices can be discovered. You can call [ble.stopBLEScan](#blestopblescan) to stop the BLE scan. 157- This API supports only single-channel scans. That is, the application can call this API only once at a time. Before calling this API again, you need to call [ble.stopBLEScan](#blestopblescan) to stop the previous scan. 158- To use multi-channel scans, call [BleScanner](#blescanner15). 159 160**Required permissions**: ohos.permission.ACCESS_BLUETOOTH 161 162**Atomic service API**: This API can be used in atomic services since API version 12. 163 164**System capability**: SystemCapability.Communication.Bluetooth.Core 165 166**Parameters** 167 168| Name | Type | Mandatory | Description | 169| ------- | -------------------------------------- | ---- | ----------------------------------- | 170| filters | Array<[ScanFilter](#scanfilter)> | Yes | Rules for filtering the scan result. Devices that meet the filtering rules will be retained.<br>If this parameter is set to **null**, all discoverable BLE devices nearby will be scanned. However, this method is not recommended as it may pick up unexpected devices and increase power consumption.| 171| options | [ScanOptions](#scanoptions) | No | Scan options. | 172 173**Error codes** 174 175For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Bluetooth Error Codes](errorcode-bluetoothManager.md). 176 177| ID| Error Message| 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**Example** 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 216Stops BLE scanning. 217- You can call [ble.startBLEScan](#blestartblescan) to stop the BLE scan. 218- Call this API to stop the Bluetooth scan if device discovery is no longer needed. 219- Scan results will not be reported after this API is called. You need to start a Bluetooth scan again for device discovery. 220 221**Required permissions**: ohos.permission.ACCESS_BLUETOOTH 222 223**Atomic service API**: This API can be used in atomic services since API version 12. 224 225**System capability**: SystemCapability.Communication.Bluetooth.Core 226 227**Error codes** 228 229For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Bluetooth Error Codes](errorcode-bluetoothManager.md). 230 231| ID| Error Message| 232| -------- | ---------------------------- | 233|201 | Permission denied. | 234|801 | Capability not supported. | 235|2900001 | Service stopped. | 236|2900003 | Bluetooth disabled. | 237|2900099 | Operation failed. | 238 239**Example** 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 255Starts sending BLE advertising packets. 256- Call [ble.stopAdvertising](#blestopadvertising) if the application no longer needs to send BLE advertising packets. 257- This API works in synchronous mode. It cannot be used with [ble.stopAdvertising](#blestopadvertising11) of API version 11. 258 259 260**Required permissions**: ohos.permission.ACCESS_BLUETOOTH 261 262**Atomic service API**: This API can be used in atomic services since API version 12. 263 264**System capability**: SystemCapability.Communication.Bluetooth.Core 265 266**Parameters** 267 268| Name | Type | Mandatory | Description | 269| ----------- | ------------------------------------- | ---- | -------------- | 270| setting | [AdvertiseSetting](#advertisesetting) | Yes | Settings related to BLE advertising. | 271| advData | [AdvertiseData](#advertisedata) | Yes | BLE advertising data. | 272| advResponse | [AdvertiseData](#advertisedata) | No | BLE advertising response.| 273 274**Error codes** 275 276For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Bluetooth Error Codes](errorcode-bluetoothManager.md). 277 278| ID| Error Message| 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**Example** 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 341Stops sending BLE advertising packets. 342- This API works for BLE advertising initiated by [ble.startAdvertising](#blestartadvertising). 343- This API cannot be used with [ble.startAdvertising](#blestartadvertising11) of API version 11. 344- Call this API if the application no longer needs to send BLE advertising packets. 345 346**Required permissions**: ohos.permission.ACCESS_BLUETOOTH 347 348**Atomic service API**: This API can be used in atomic services since API version 12. 349 350**System capability**: SystemCapability.Communication.Bluetooth.Core 351 352**Error codes** 353 354For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Bluetooth Error Codes](errorcode-bluetoothManager.md). 355 356| ID| Error Message| 357| -------- | ---------------------------- | 358|201 | Permission denied. | 359|801 | Capability not supported. | 360|2900001 | Service stopped. | 361|2900003 | Bluetooth disabled. | 362|2900099 | Operation failed. | 363 364**Example** 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 380Starts sending BLE advertising packets for the first time. This API uses an asynchronous callback to return the result. 381- After this API is called, the Bluetooth subsystem allocates related resources and returns the advertising ID using an asynchronous callback. 382- If the advertising duration is specified, advertising will stop after the duration elapses, but the allocated advertising resources will remain. You can call [ble.enableAdvertising](#bleenableadvertising11) to enable advertising again. 383- Since API version 15, you can call this API multiple times to establish multiple advertising channels, each being identified by a unique ID. 384- Call [ble.stopAdvertising](#blestopadvertising11) (supported since API version 11) if advertising is no longer needed. Do not use this API with [ble.stopAdvertising](#blestopadvertising) (supported since API version 10). 385 386**Required permissions**: ohos.permission.ACCESS_BLUETOOTH 387 388**System capability**: SystemCapability.Communication.Bluetooth.Core 389 390**Parameters** 391 392| Name | Type | Mandatory | Description | 393| ------------------- | --------------------------------------- | ----- | ------------------------------- | 394| advertisingParams | [AdvertisingParams](#advertisingparams11) | Yes | Parameters for starting BLE advertising. | 395| callback | AsyncCallback<number> | Yes | Callback used to return the advertisement ID.| 396 397**Error codes** 398 399For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Bluetooth Error Codes](errorcode-bluetoothManager.md). 400 401| ID| Error Message| 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**Example** 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 478Starts sending BLE advertising packets for the first time. This API uses a promise to return the result. 479- After this API is called, the Bluetooth subsystem allocates related resources and returns the advertising ID using a promise. 480- If the advertising duration is specified, advertising will stop after the duration elapses, but the allocated advertising resources will remain. You can call [ble.enableAdvertising](#bleenableadvertising11) to enable advertising again. 481- Since API version 15, you can call this API multiple times to establish multiple advertising channels, each being identified by a unique ID. 482- Call [ble.stopAdvertising](#blestopadvertising11-1) (supported since API version 11) if advertising is no longer needed. Do not use this API with [ble.stopAdvertising](#blestopadvertising) (supported since API version 10). 483 484**Required permissions**: ohos.permission.ACCESS_BLUETOOTH 485 486**System capability**: SystemCapability.Communication.Bluetooth.Core 487 488**Parameters** 489 490| Name | Type | Mandatory | Description | 491| ------------------- | -------------------------------------- | ----- | ----------------------- | 492| advertisingParams | [AdvertisingParams](#advertisingparams11) | Yes | Parameters for starting BLE advertising. | 493 494**Return value** 495 496| Type | Description | 497| -------------------------- | ------------------------------- | 498| Promise<number> | Promise used to return the BLE advertisement ID.| 499 500**Error codes** 501 502For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Bluetooth Error Codes](errorcode-bluetoothManager.md). 503 504| ID| Error Message| 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**Example** 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 577Enables BLE advertising based on the specified **advertisingId**. This API uses an asynchronous callback to return the result. 578- The advertising resource corresponding to **advertisingId** in [AdvertisingEnableParams](#advertisingenableparams11) has been allocated when [ble.startAdvertising](#blestartadvertising11) is called to start BLE for the first time. 579- If the advertising duration is specified in [ble.startAdvertising](#blestartadvertising11), advertising will stop after the duration elapses. You can call this API to enable advertising again. 580- If advertising is disabled by calling [ble.disableAdvertising](#bledisableadvertising11), you can call this API to enable advertising again. 581- You can obtain the operation result through the callback of [ble.on('advertisingStateChange')](#bleonadvertisingstatechange11). 582 583**Required permissions**: ohos.permission.ACCESS_BLUETOOTH 584 585**System capability**: SystemCapability.Communication.Bluetooth.Core 586 587**Parameters** 588 589| Name | Type | Mandatory | Description | 590| ------------------------- | --------------------------------------------------- | ----- | ------------------------------- | 591| advertisingEnableParams | [AdvertisingEnableParams](#advertisingenableparams11) | Yes | Parameters for temporarily enabling BLE advertising. | 592| callback | AsyncCallback<void> | Yes | Callback used to return the result. | 593 594**Error codes** 595 596For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Bluetooth Error Codes](errorcode-bluetoothManager.md). 597 598| ID| Error Message| 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**Example** 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 686Enables BLE advertising based on the specified **advertisingId**. This API uses a promise to return the result. 687- The advertising resource corresponding to **advertisingId** in [AdvertisingEnableParams](#advertisingenableparams11) has been allocated when [ble.startAdvertising](#blestartadvertising11) is called to start BLE for the first time. 688- If the advertising duration is specified in [ble.startAdvertising](#blestartadvertising11), advertising will stop after the duration elapses. You can call this API to enable advertising again. 689- If advertising is disabled by calling [ble.disableAdvertising](#bledisableadvertising11), you can call this API to enable advertising again. 690- You can obtain the operation result through the callback of [ble.on('advertisingStateChange')](#bleonadvertisingstatechange11). 691 692**Required permissions**: ohos.permission.ACCESS_BLUETOOTH 693 694**System capability**: SystemCapability.Communication.Bluetooth.Core 695 696**Parameters** 697 698| Name | Type | Mandatory | Description | 699| ------------------------- | --------------------------------------------------- | ----- | ------------------------------- | 700| advertisingEnableParams | [AdvertisingEnableParams](#advertisingenableparams11) | Yes | Parameters for temporarily enabling BLE advertising. | 701 702**Return value** 703 704| Type | Description | 705| -------------------------- | ------------ | 706| Promise<void> | Promise used to return the result. | 707 708**Error codes** 709 710For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Bluetooth Error Codes](errorcode-bluetoothManager.md). 711 712| ID| Error Message| 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**Example** 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 799Disables BLE advertising based on the specified **advertisingId**. This API uses an asynchronous callback to return the result. 800- After this API is called, advertising will stop, but the allocated advertising resources will remain. You can call [ble.enableAdvertising](#bleenableadvertising11) to enable advertising again. 801- The advertising resource corresponding to **advertisingId** in [AdvertisingDisableParams](#advertisingdisableparams11) has been allocated when [ble.startAdvertising](#blestartadvertising11) is called to start BLE for the first time. 802- You can obtain the operation result through the callback of [ble.on('advertisingStateChange')](#bleonadvertisingstatechange11). 803 804**Required permissions**: ohos.permission.ACCESS_BLUETOOTH 805 806**System capability**: SystemCapability.Communication.Bluetooth.Core 807 808**Parameters** 809 810| Name | Type | Mandatory | Description | 811| ------------------------- | ----------------------------------------------------- | ----- | ------------------------------- | 812| advertisingDisableParams | [AdvertisingDisableParams](#advertisingdisableparams11) | Yes | Parameters for temporarily disabling BLE advertising. | 813| callback | AsyncCallback<void> | Yes | Callback used to return the result. | 814 815**Error codes** 816 817For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Bluetooth Error Codes](errorcode-bluetoothManager.md). 818 819| ID| Error Message| 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**Example** 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 904Disables BLE advertising based on the specified **advertisingId**. This API uses a promise to return the result. 905- After this API is called, advertising will stop, but the allocated advertising resources will remain. You can call [ble.enableAdvertising](#bleenableadvertising11) to enable advertising again. 906- The advertising resource corresponding to **advertisingId** in [AdvertisingDisableParams](#advertisingdisableparams11) has been allocated when [ble.startAdvertising](#blestartadvertising11) is called to start BLE for the first time. 907- You can obtain the operation result through the callback of [ble.on('advertisingStateChange')](#bleonadvertisingstatechange11). 908 909**Required permissions**: ohos.permission.ACCESS_BLUETOOTH 910 911**System capability**: SystemCapability.Communication.Bluetooth.Core 912 913**Parameters** 914 915| Name | Type | Mandatory | Description | 916| ------------------------- | ----------------------------------------------------- | ----- | ------------------------------- | 917| advertisingDisableParams | [AdvertisingDisableParams](#advertisingdisableparams11) | Yes | Parameters for temporarily disabling BLE advertising. | 918 919**Return value** 920 921| Type | Description | 922| -------------------------- | ------------ | 923| Promise<void> | Promise used to return the result. | 924 925**Error codes** 926 927For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Bluetooth Error Codes](errorcode-bluetoothManager.md). 928 929| ID| Error Message| 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**Example** 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 1012Stops sending BLE advertising packets. This API uses an asynchronous callback to return the result. 1013- If this API is used with [ble.startAdvertising](#blestartadvertising11) (supported since API version 11), the requested advertising resources will be released. 1014- The **advertisingId** allocated when [ble.startAdvertising](#blestartadvertising11) is called to start advertising for the first time will also become invalid. 1015- This API cannot be used with [ble.startAdvertising](#blestartadvertising) (supported since API version 10). 1016- You can obtain the operation result through the callback of [ble.on('advertisingStateChange')](#bleonadvertisingstatechange11). 1017 1018**Required permissions**: ohos.permission.ACCESS_BLUETOOTH 1019 1020**System capability**: SystemCapability.Communication.Bluetooth.Core 1021 1022**Parameters** 1023 1024| Name | Type | Mandatory | Description | 1025| ------------------------- | ---------------------------- | ----- | --------------------------- | 1026| advertisingId | number | Yes | ID of the advertisement to stop. | 1027| callback | AsyncCallback<void> | Yes | Callback used to return the result. | 1028 1029**Error codes** 1030 1031For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Bluetooth Error Codes](errorcode-bluetoothManager.md). 1032 1033| ID| Error Message| 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**Example** 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 1115Stops sending BLE advertising packets. This API uses a promise to return the result. 1116- If this API is used with [ble.startAdvertising](#blestartadvertising11) (supported since API version 11), the requested advertising resources will be released. 1117- The **advertisingId** allocated when [ble.startAdvertising](#blestartadvertising11) is called to start advertising for the first time will also become invalid. 1118- This API cannot be used with [ble.startAdvertising](#blestartadvertising) (supported since API version 10). 1119- You can obtain the operation result through the callback of [ble.on('advertisingStateChange')](#bleonadvertisingstatechange11). 1120 1121**Required permissions**: ohos.permission.ACCESS_BLUETOOTH 1122 1123**System capability**: SystemCapability.Communication.Bluetooth.Core 1124 1125**Parameters** 1126 1127| Name | Type | Mandatory | Description | 1128| ------------------------- | ---------------------------- | ----- | --------------------------- | 1129| advertisingId | number | Yes | ID of the advertisement to stop. | 1130 1131**Return value** 1132 1133| Type | Description | 1134| -------------------------- | ------------ | 1135| Promise<void> | Promise used to return the result. | 1136 1137**Error codes** 1138 1139For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Bluetooth Error Codes](errorcode-bluetoothManager.md). 1140 1141| ID| Error Message| 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**Example** 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 1222Subscribes to BLE advertising status. This API uses an asynchronous callback to return the result. 1223 1224**Required permissions**: ohos.permission.ACCESS_BLUETOOTH 1225 1226**System capability**: SystemCapability.Communication.Bluetooth.Core 1227 1228**Parameters** 1229 1230| Name | Type | Mandatory | Description | 1231| -------- | ------------------------------------------------------------------------- | ----- | ---------------------------------------------------------- | 1232| type | string | Yes | Event type. The value **advertisingStateChange** indicates an advertising state change event.<br>This event is triggered if the advertising state changes when [ble.startAdvertising](#blestartadvertising11), [ble.stopAdvertising](#blestopadvertising11), [ble.enableAdvertising](#bleenableadvertising11) or [ble.disableAdvertising](#bledisableadvertising11) is called. | 1233| callback | Callback<[AdvertisingStateChangeInfo](#advertisingstatechangeinfo11)> | Yes | Callback used to return the advertising state change event.| 1234 1235**Error codes** 1236 1237For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Bluetooth Error Codes](errorcode-bluetoothManager.md). 1238 1239| ID| Error Message| 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**Example** 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 1265Unsubscribes from BLE advertising status. No BLE advertising state change events will be received when BLE advertising is stopped or started. 1266 1267**Required permissions**: ohos.permission.ACCESS_BLUETOOTH 1268 1269**System capability**: SystemCapability.Communication.Bluetooth.Core 1270 1271**Parameters** 1272 1273| Name | Type | Mandatory | Description | 1274| -------- | ------------------------------------------------------------------------- | ----- | ---------------------------------------------------------- | 1275| type | string | Yes | Event type. The value **advertisingStateChange** indicates an advertising state change event. | 1276| callback | Callback<[AdvertisingStateChangeInfo](#advertisingstatechangeinfo11)> | No | Callback to unregister.<br>If this parameter is specified, it must be the same as the callback in [ble.on('advertisingStateChange')](#bleonadvertisingstatechange11). If this parameter is not specified, all callbacks corresponding to the event type are unsubscribed.| 1277 1278**Error codes** 1279 1280For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Bluetooth Error Codes](errorcode-bluetoothManager.md). 1281 1282| ID| Error Message| 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**Example** 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 1309Subscribes to BLE scan result reporting events. This API uses an asynchronous callback to return the result. 1310 1311**Required permissions**: ohos.permission.ACCESS_BLUETOOTH 1312 1313**Atomic service API**: This API can be used in atomic services since API version 12. 1314 1315**System capability**: SystemCapability.Communication.Bluetooth.Core 1316 1317**Parameters** 1318 1319| Name | Type | Mandatory | Description | 1320| -------- | ---------------------------------------- | ---- | ----------------------------------- | 1321| type | string | Yes | Event type. The value **BLEDeviceFind** indicates a scan result reporting event.<br>This event is triggered if a BLE device is discovered when [ble.startBLEScan](#blestartblescan) is called.| 1322| callback | Callback<Array<[ScanResult](#scanresult)>> | Yes | Callback used to return the set of scan results.| 1323 1324**Error codes** 1325 1326For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Bluetooth Error Codes](errorcode-bluetoothManager.md). 1327 1328| ID| Error Message| 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**Example** 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 1354Unsubscribes from BLE scan result reporting events. 1355- After [ble.stopBLEScan](#blestopblescan) is called to stop the BLE scan, call this API to unsubscribe from scan result reporting events if device discovery is no longer needed. 1356 1357**Required permissions**: ohos.permission.ACCESS_BLUETOOTH 1358 1359**Atomic service API**: This API can be used in atomic services since API version 12. 1360 1361**System capability**: SystemCapability.Communication.Bluetooth.Core 1362 1363**Parameters** 1364 1365| Name | Type | Mandatory | Description | 1366| -------- | ---------------------------------------- | ---- | ---------------------------------------- | 1367| type | string | Yes | Event type. The value **BLEDeviceFind** indicates a scan result reporting event. | 1368| callback | Callback<Array<[ScanResult](#scanresult)>> | No | Callback to unregister.<br>If this parameter is specified, it must be the same as the callback in [ble.on('BLEDeviceFind')](#bleonbledevicefind). If this parameter is not specified, all callbacks corresponding to the event type are unsubscribed.| 1369 1370**Error codes** 1371 1372For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Bluetooth Error Codes](errorcode-bluetoothManager.md). 1373 1374 1375| ID| Error Message| 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**Example** 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 1400Represents a GATT server. 1401- You can use [ble.createGattServer](#blecreategattserver) to create a server instance. 1402- You can use this instance to operate the server, for example, call [addService](#addservice) to add a server and use [notifyCharacteristicChanged](#notifycharacteristicchanged) report characteristic changes. 1403 1404 1405### addService 1406 1407addService(service: GattService): void 1408 1409Adds a service to this GATT server. This operation registers the service with the Bluetooth subsystem to indicate the capabilities supported by the server. 1410 1411**Required permissions**: ohos.permission.ACCESS_BLUETOOTH 1412 1413**Atomic service API**: This API can be used in atomic services since API version 12. 1414 1415**System capability**: SystemCapability.Communication.Bluetooth.Core 1416 1417**Parameters** 1418 1419| Name | Type | Mandatory | Description | 1420| ------- | --------------------------- | ---- | ------------------------ | 1421| service | [GattService](#gattservice) | Yes | Service data, which indicates the functions supported by the server.<br>For example, **00001800-0000-1000-8000-00805f9b34fb** indicates the general access service, and **00001801-0000-1000-8000-00805f9b34fb** indicates the general characteristic service.| 1422 1423**Error codes** 1424 1425For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Bluetooth Error Codes](errorcode-bluetoothManager.md). 1426 1427| ID| Error Message| 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**Example** 1437 1438```js 1439import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 1440// Create descriptors. 1441let descriptors: Array<ble.BLEDescriptor> = []; 1442let arrayBuffer = new ArrayBuffer(2); 1443let descV = new Uint8Array(arrayBuffer); 1444descV[0] = 0; // Use the Client Characteristic Configuration descriptor as an example. When bit 0 and bit 1 are both set to 0, the notification and indication functions are disabled. 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// Create 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// Create a gattService instance. 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 1475Deletes a service added to the server. 1476- The service has been added by calling [addService](#addservice). 1477 1478**Required permissions**: ohos.permission.ACCESS_BLUETOOTH 1479 1480**Atomic service API**: This API can be used in atomic services since API version 12. 1481 1482**System capability**: SystemCapability.Communication.Bluetooth.Core 1483 1484**Parameters** 1485 1486| Name | Type | Mandatory | Description | 1487| ----------- | ------ | ---- | ---------------------------------------- | 1488| serviceUuid | string | Yes | UUID of the service to be deleted, for example, 00001810-0000-1000-8000-00805F9B34FB.| 1489 1490**Error codes** 1491 1492For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Bluetooth Error Codes](errorcode-bluetoothManager.md). 1493 1494| ID| Error Message| 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**Example** 1505 1506```js 1507import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 1508let server: ble.GattServer = ble.createGattServer(); 1509try { 1510 // Before removeService is called, the server and the client must be paired and connected. 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 1522Closes the server instance. The instance created by calling [ble.createGattServer](#blecreategattserver) is unavailable after being closed. 1523 1524**Required permissions**: ohos.permission.ACCESS_BLUETOOTH 1525 1526**Atomic service API**: This API can be used in atomic services since API version 12. 1527 1528**System capability**: SystemCapability.Communication.Bluetooth.Core 1529 1530**Error codes** 1531 1532For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Bluetooth Error Codes](errorcode-bluetoothManager.md). 1533 1534| ID| Error Message| 1535| -------- | ---------------------------- | 1536|201 | Permission denied. | 1537|801 | Capability not supported. | 1538|2900001 | Service stopped. | 1539|2900003 | Bluetooth disabled. | 1540|2900099 | Operation failed. | 1541 1542**Example** 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 1559Sends a characteristic change notification or indication from the server to the client. This API uses an asynchronous callback to return the result. 1560 1561- You are advised to enable the notification or indication function for the Client Characteristic Configuration descriptor (UUID: 00002902-0000-1000-8000-00805f9b34fb) of the characteristic. 1562- According to the Bluetooth protocol, the data length of the Client Characteristic Configuration descriptor is 2 bytes. Bit 0 and bit 1 indicate whether notification and indication are enabled, respectively. For example, **bit 0 = 1** indicates that notification is enabled. 1563- This API is called when the properties of a GATT characteristic change. 1564 1565**Required permissions**: ohos.permission.ACCESS_BLUETOOTH 1566 1567**Atomic service API**: This API can be used in atomic services since API version 12. 1568 1569**System capability**: SystemCapability.Communication.Bluetooth.Core 1570 1571**Parameters** 1572 1573| Name | Type | Mandatory | Description | 1574| -------------------- | ---------------------------------------- | ---- | --------------------------------------- | 1575| deviceId | string | Yes | Client address, for example, XX:XX:XX:XX:XX:XX.| 1576| notifyCharacteristic | [NotifyCharacteristic](#notifycharacteristic) | Yes | Characteristic object. | 1577| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.| 1578 1579**Error codes** 1580 1581For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Bluetooth Error Codes](errorcode-bluetoothManager.md). 1582 1583| ID| Error Message| 1584| -------- | ---------------------------- | 1585|201 | Permission denied. | 1586|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 1587|801 | Capability not supported. | 1588|2900001 | Service stopped. | 1589|2900003 | Bluetooth disabled. | 1590|2900099 | Operation failed. | 1591 1592**Example** 1593 1594```js 1595import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 1596let arrayBufferC = new ArrayBuffer(8); 1597let notifyCharacter: ble.NotifyCharacteristic = { 1598 serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', 1599 characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', 1600 characteristicValue: arrayBufferC, 1601 confirm: true 1602}; 1603try { 1604 let gattServer: ble.GattServer = ble.createGattServer(); 1605 gattServer.notifyCharacteristicChanged('XX:XX:XX:XX:XX:XX', notifyCharacter, (err: BusinessError) => { 1606 if (err) { 1607 console.error('notifyCharacteristicChanged callback failed'); 1608 } else { 1609 console.info('notifyCharacteristicChanged callback successful'); 1610 } 1611 }); 1612} catch (err) { 1613 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 1614} 1615``` 1616 1617 1618### notifyCharacteristicChanged 1619 1620notifyCharacteristicChanged(deviceId: string, notifyCharacteristic: NotifyCharacteristic): Promise<void> 1621 1622Sends a characteristic change event from the server to the client. This API uses a promise to return the result. 1623 1624- You are advised to enable notification or indication for the Client Characteristic Configuration descriptor of the characteristic. 1625- According to the Bluetooth protocol, the data length of the Client Characteristic Configuration descriptor is 2 bytes. Bit 0 and bit 1 indicate whether notification and indication are enabled, respectively. For example, **bit 0 = 1** indicates that notification is enabled. 1626- This API is called when the properties of a GATT characteristic change. 1627 1628**Required permissions**: ohos.permission.ACCESS_BLUETOOTH 1629 1630**Atomic service API**: This API can be used in atomic services since API version 12. 1631 1632**System capability**: SystemCapability.Communication.Bluetooth.Core 1633 1634**Parameters** 1635 1636| Name | Type | Mandatory | Description | 1637| -------------------- | ---------------------------------------- | ---- | --------------------------------------- | 1638| deviceId | string | Yes | Client address, for example, XX:XX:XX:XX:XX:XX.| 1639| notifyCharacteristic | [NotifyCharacteristic](#notifycharacteristic) | Yes | Characteristic object. | 1640 1641**Return value** 1642 1643| Type | Description | 1644| ------------------- | ------------- | 1645| Promise<void> | Promise that returns no value.| 1646 1647**Error codes** 1648 1649For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Bluetooth Error Codes](errorcode-bluetoothManager.md). 1650 1651| ID| Error Message| 1652| -------- | ---------------------------- | 1653|201 | Permission denied. | 1654|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 1655|801 | Capability not supported. | 1656|2900001 | Service stopped. | 1657|2900003 | Bluetooth disabled. | 1658|2900099 | Operation failed. | 1659 1660**Example** 1661 1662```js 1663import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 1664let arrayBufferC = new ArrayBuffer(8); 1665let notifyCharacter: ble.NotifyCharacteristic = { 1666 serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', 1667 characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', 1668 characteristicValue: arrayBufferC, 1669 confirm: true 1670}; 1671try { 1672 let gattServer: ble.GattServer = ble.createGattServer(); 1673 gattServer.notifyCharacteristicChanged('XX:XX:XX:XX:XX:XX', notifyCharacter).then(() => { 1674 console.info('notifyCharacteristicChanged promise successful'); 1675 }); 1676} catch (err) { 1677 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 1678} 1679``` 1680 1681 1682### sendResponse 1683 1684sendResponse(serverResponse: ServerResponse): void 1685 1686Sends a response to a client request. This helps to prevent a connection from being disconnected due to a timeout. 1687 1688A client request is received through the following APIs: 1689 1690- [on('characteristicRead')](#oncharacteristicread) 1691- [on('characteristicWrite')](#oncharacteristicwrite) (Whether a response is needed is determined based on **needRsp** in [CharacteristicWriteRequest](#characteristicwriterequest)). 1692- [on('descriptorRead')](#ondescriptorread) 1693- [on('descriptorWrite')](#ondescriptorwrite) (Whether a response is needed is determined by **needRsp** in [DescriptorWriteRequest](#descriptorwriterequest)). 1694 1695**Required permissions**: ohos.permission.ACCESS_BLUETOOTH 1696 1697**Atomic service API**: This API can be used in atomic services since API version 12. 1698 1699**System capability**: SystemCapability.Communication.Bluetooth.Core 1700 1701**Parameters** 1702 1703| Name | Type | Mandatory | Description | 1704| -------------- | --------------------------------- | ---- | --------------- | 1705| serverResponse | [ServerResponse](#serverresponse) | Yes | Response returned by the GATT server.| 1706 1707**Error codes** 1708 1709For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Bluetooth Error Codes](errorcode-bluetoothManager.md). 1710 1711| ID| Error Message| 1712| -------- | ---------------------------- | 1713|201 | Permission denied. | 1714|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 1715|801 | Capability not supported. | 1716|2900001 | Service stopped. | 1717|2900003 | Bluetooth disabled. | 1718|2900099 | Operation failed. | 1719 1720**Example** 1721 1722```js 1723import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 1724/* send response */ 1725let arrayBufferCCC = new ArrayBuffer(8); 1726let cccValue = new Uint8Array(arrayBufferCCC); 1727cccValue[0] = 1; 1728let serverResponse: ble.ServerResponse = { 1729 deviceId: 'XX:XX:XX:XX:XX:XX', 1730 transId: 0, 1731 status: 0, 1732 offset: 0, 1733 value: arrayBufferCCC 1734}; 1735try { 1736 let gattServer: ble.GattServer = ble.createGattServer(); 1737 gattServer.sendResponse(serverResponse); 1738} catch (err) { 1739 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 1740} 1741``` 1742 1743 1744### on('characteristicRead') 1745 1746on(type: 'characteristicRead', callback: Callback<CharacteristicReadRequest>): void 1747 1748Subscribes to characteristic read request events of the client. After receiving the event, the server needs to call [sendResponse](#sendresponse) to send a response to the client. This API uses an asynchronous callback to return the result. 1749 1750**Required permissions**: ohos.permission.ACCESS_BLUETOOTH 1751 1752**Atomic service API**: This API can be used in atomic services since API version 12. 1753 1754**System capability**: SystemCapability.Communication.Bluetooth.Core 1755 1756**Parameters** 1757 1758| Name | Type | Mandatory | Description | 1759| -------- | ---------------------------------------- | ---- | ------------------------------------- | 1760| type | string | Yes | Event type. The value **characteristicRead** indicates a characteristic read request event.<br>This event is triggered when the server receives a characteristic read request from the client.| 1761| callback | Callback<[CharacteristicReadRequest](#characteristicreadrequest)> | Yes | Callback used to return the read request event. | 1762 1763**Error codes** 1764 1765For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 1766 1767| ID| Error Message| 1768| -------- | ---------------------------- | 1769|201 | Permission denied. | 1770|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 1771|801 | Capability not supported. | 1772 1773**Example** 1774 1775```js 1776import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 1777let arrayBufferCCC = new ArrayBuffer(8); 1778let cccValue = new Uint8Array(arrayBufferCCC); 1779cccValue[0] = 1; 1780let gattServer: ble.GattServer = ble.createGattServer(); 1781function ReadCharacteristicReq(characteristicReadRequest: ble.CharacteristicReadRequest) { 1782 let deviceId: string = characteristicReadRequest.deviceId; 1783 let transId: number = characteristicReadRequest.transId; 1784 let offset: number = characteristicReadRequest.offset; 1785 let characteristicUuid: string = characteristicReadRequest.characteristicUuid; 1786 1787 let serverResponse: ble.ServerResponse = {deviceId: deviceId, transId: transId, status: 0, offset: offset, value:arrayBufferCCC}; 1788 1789 try { 1790 gattServer.sendResponse(serverResponse); 1791 } catch (err) { 1792 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 1793 } 1794} 1795gattServer.on('characteristicRead', ReadCharacteristicReq); 1796``` 1797 1798 1799### off('characteristicRead') 1800 1801off(type: 'characteristicRead', callback?: Callback<CharacteristicReadRequest>): void 1802 1803Unsubscribes from characteristic read request events. 1804 1805**Required permissions**: ohos.permission.ACCESS_BLUETOOTH 1806 1807**Atomic service API**: This API can be used in atomic services since API version 12. 1808 1809**System capability**: SystemCapability.Communication.Bluetooth.Core 1810 1811**Parameters** 1812 1813| Name | Type | Mandatory | Description | 1814| -------- | ---------------------------------------- | ---- | ---------------------------------------- | 1815| type | string | Yes | Event type. The value **characteristicRead** indicates a characteristic read request event. | 1816| callback | Callback<[CharacteristicReadRequest](#characteristicreadrequest)> | No | Callback to unregister.<br>If this parameter is specified, it must be the same as the callback in [on('characteristicRead')](#oncharacteristicread). If this parameter is not specified, all callbacks corresponding to the event type are unsubscribed.| 1817 1818**Error codes** 1819 1820For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 1821 1822| ID| Error Message| 1823| -------- | ---------------------------- | 1824|201 | Permission denied. | 1825|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 1826|801 | Capability not supported. | 1827 1828**Example** 1829 1830```js 1831import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 1832try { 1833 let gattServer: ble.GattServer = ble.createGattServer(); 1834 gattServer.off('characteristicRead'); 1835} catch (err) { 1836 console.error("errCode:" + (err as BusinessError).code + ",errMessage:" + (err as BusinessError).message); 1837} 1838``` 1839 1840 1841### on('characteristicWrite') 1842 1843on(type: 'characteristicWrite', callback: Callback<CharacteristicWriteRequest>): void 1844 1845Subscribes to characteristic write request events of the client. After receiving such an event, the server determines whether to call [sendResponse](#sendresponse) to send a response to the client based on the **needRsp** in [CharacteristicWriteRequest](#characteristicwriterequest). 1846 1847**Required permissions**: ohos.permission.ACCESS_BLUETOOTH 1848 1849**Atomic service API**: This API can be used in atomic services since API version 12. 1850 1851**System capability**: SystemCapability.Communication.Bluetooth.Core 1852 1853**Parameters** 1854 1855| Name | Type | Mandatory | Description | 1856| -------- | ---------------------------------------- | ---- | -------------------------------------- | 1857| type | string | Yes | Event type. The value **characteristicWrite** indicates a characteristic write request event.<br>This event is triggered when the server receives a characteristic write request from the client.| 1858| callback | Callback<[CharacteristicWriteRequest](#characteristicwriterequest)> | Yes | Callback used to return the write request event. | 1859 1860**Error codes** 1861 1862For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 1863 1864| ID| Error Message| 1865| -------- | ---------------------------- | 1866|201 | Permission denied. | 1867|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 1868|801 | Capability not supported. | 1869 1870**Example** 1871 1872```js 1873import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 1874let arrayBufferCCC = new ArrayBuffer(8); 1875let cccValue = new Uint8Array(arrayBufferCCC); 1876let gattServer: ble.GattServer = ble.createGattServer(); 1877function WriteCharacteristicReq(characteristicWriteRequest: ble.CharacteristicWriteRequest) { 1878 let deviceId: string = characteristicWriteRequest.deviceId; 1879 let transId: number = characteristicWriteRequest.transId; 1880 let offset: number = characteristicWriteRequest.offset; 1881 let isPrepared: boolean = characteristicWriteRequest.isPrepared; 1882 let needRsp: boolean = characteristicWriteRequest.needRsp; 1883 let value: Uint8Array = new Uint8Array(characteristicWriteRequest.value); 1884 let characteristicUuid: string = characteristicWriteRequest.characteristicUuid; 1885 1886 cccValue[0] = value[0]; 1887 let serverResponse: ble.ServerResponse = {deviceId: deviceId, transId: transId, status: 0, offset: offset, value:arrayBufferCCC}; 1888 1889 try { 1890 gattServer.sendResponse(serverResponse); 1891 } catch (err) { 1892 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 1893 } 1894} 1895gattServer.on('characteristicWrite', WriteCharacteristicReq); 1896``` 1897 1898 1899### off('characteristicWrite') 1900 1901off(type: 'characteristicWrite', callback?: Callback<CharacteristicWriteRequest>): void 1902 1903Unsubscribes from characteristic write request events. 1904 1905**Required permissions**: ohos.permission.ACCESS_BLUETOOTH 1906 1907**Atomic service API**: This API can be used in atomic services since API version 12. 1908 1909**System capability**: SystemCapability.Communication.Bluetooth.Core 1910 1911**Parameters** 1912 1913| Name | Type | Mandatory | Description | 1914| -------- | ---------------------------------------- | ---- | ---------------------------------------- | 1915| type | string | Yes | Event type. The value **characteristicWrite** indicates a characteristic write request event. | 1916| callback | Callback<[CharacteristicWriteRequest](#characteristicwriterequest)> | No | Callback to unregister.<br>If this parameter is specified, it must be the same as the callback in [on('characteristicWrite')](#oncharacteristicwrite). If this parameter is not specified, all callbacks corresponding to the event type are unsubscribed.| 1917 1918**Error codes** 1919 1920For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 1921 1922| ID| Error Message| 1923| -------- | ---------------------------- | 1924|201 | Permission denied. | 1925|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 1926|801 | Capability not supported. | 1927 1928**Example** 1929 1930```js 1931import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 1932try { 1933 let gattServer: ble.GattServer = ble.createGattServer(); 1934 gattServer.off('characteristicWrite'); 1935} catch (err) { 1936 console.error("errCode:" + (err as BusinessError).code + ",errMessage:" + (err as BusinessError).message); 1937} 1938``` 1939 1940 1941### on('descriptorRead') 1942 1943on(type: 'descriptorRead', callback: Callback<DescriptorReadRequest>): void 1944 1945Subscribes to descriptor read request events of the client. After receiving the event, the server needs to call [sendResponse](#sendresponse) to send a response to the client. 1946 1947**Required permissions**: ohos.permission.ACCESS_BLUETOOTH 1948 1949**Atomic service API**: This API can be used in atomic services since API version 12. 1950 1951**System capability**: SystemCapability.Communication.Bluetooth.Core 1952 1953**Parameters** 1954 1955| Name | Type | Mandatory | Description | 1956| -------- | ---------------------------------------- | ---- | --------------------------------- | 1957| type | string | Yes | Event type. The value **descriptorRead** indicates a descriptor read request event.<br>This event is triggered when the server receives a descriptor read request from the client.| 1958| callback | Callback<[DescriptorReadRequest](#descriptorreadrequest)> | Yes | Callback used to return the read request event. | 1959 1960**Error codes** 1961 1962For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 1963 1964| ID| Error Message| 1965| -------- | ---------------------------- | 1966|201 | Permission denied. | 1967|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 1968|801 | Capability not supported. | 1969 1970**Example** 1971 1972```js 1973import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 1974let arrayBufferDesc = new ArrayBuffer(8); 1975let descValue = new Uint8Array(arrayBufferDesc); 1976descValue[0] = 1; 1977let gattServer: ble.GattServer = ble.createGattServer(); 1978function ReadDescriptorReq(descriptorReadRequest: ble.DescriptorReadRequest) { 1979 let deviceId: string = descriptorReadRequest.deviceId; 1980 let transId: number = descriptorReadRequest.transId; 1981 let offset: number = descriptorReadRequest.offset; 1982 let descriptorUuid: string = descriptorReadRequest.descriptorUuid; 1983 1984 let serverResponse: ble.ServerResponse = {deviceId: deviceId, transId: transId, status: 0, offset: offset, value:arrayBufferDesc}; 1985 1986 try { 1987 gattServer.sendResponse(serverResponse); 1988 } catch (err) { 1989 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 1990 } 1991} 1992gattServer.on('descriptorRead', ReadDescriptorReq); 1993``` 1994 1995 1996### off('descriptorRead') 1997 1998off(type: 'descriptorRead', callback?: Callback<DescriptorReadRequest>): void 1999 2000Unsubscribes from descriptor read request events. 2001 2002**Required permissions**: ohos.permission.ACCESS_BLUETOOTH 2003 2004**Atomic service API**: This API can be used in atomic services since API version 12. 2005 2006**System capability**: SystemCapability.Communication.Bluetooth.Core 2007 2008**Parameters** 2009 2010| Name | Type | Mandatory | Description | 2011| -------- | ---------------------------------------- | ---- | ---------------------------------------- | 2012| type | string | Yes | Event type. The value **descriptorRead** indicates a descriptor read request event. | 2013| callback | Callback<[DescriptorReadRequest](#descriptorreadrequest)> | No | Callback to unregister.<br>If this parameter is specified, it must be the same as the callback in [on('descriptorRead')](#ondescriptorread). If this parameter is not specified, all callbacks corresponding to the event type are unsubscribed.| 2014 2015**Error codes** 2016 2017For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 2018 2019| ID| Error Message| 2020| -------- | ---------------------------- | 2021|201 | Permission denied. | 2022|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 2023|801 | Capability not supported. | 2024 2025**Example** 2026 2027```js 2028import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 2029try { 2030 let gattServer: ble.GattServer = ble.createGattServer(); 2031 gattServer.off('descriptorRead'); 2032} catch (err) { 2033 console.error("errCode:" + (err as BusinessError).code + ",errMessage:" + (err as BusinessError).message); 2034} 2035``` 2036 2037 2038### on('descriptorWrite') 2039 2040on(type: 'descriptorWrite', callback: Callback<DescriptorWriteRequest>): void 2041 2042Subscribes to descriptor write request events of the client. After receiving such an event, the server determines whether to call [sendResponse](#sendresponse) to send a response to the client based on the **needRsp** in [DescriptorWriteRequest](#descriptorwriterequest). 2043 2044**Required permissions**: ohos.permission.ACCESS_BLUETOOTH 2045 2046**Atomic service API**: This API can be used in atomic services since API version 12. 2047 2048**System capability**: SystemCapability.Communication.Bluetooth.Core 2049 2050**Parameters** 2051 2052| Name | Type | Mandatory | Description | 2053| -------- | ---------------------------------------- | ---- | ---------------------------------- | 2054| type | string | Yes | Event type. The value **descriptorWrite** indicates a descriptor write request event.<br>This event is triggered when the server receives a descriptor write request from the client.| 2055| callback | Callback<[DescriptorWriteRequest](#descriptorwriterequest)> | Yes | Callback used to return the write request event. | 2056 2057**Error codes** 2058 2059For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 2060 2061| ID| Error Message| 2062| -------- | ---------------------------- | 2063|201 | Permission denied. | 2064|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 2065|801 | Capability not supported. | 2066 2067**Example** 2068 2069```js 2070import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 2071let arrayBufferDesc = new ArrayBuffer(8); 2072let descValue = new Uint8Array(arrayBufferDesc); 2073let gattServer: ble.GattServer = ble.createGattServer(); 2074function WriteDescriptorReq(descriptorWriteRequest: ble.DescriptorWriteRequest) { 2075 let deviceId: string = descriptorWriteRequest.deviceId; 2076 let transId: number = descriptorWriteRequest.transId; 2077 let offset: number = descriptorWriteRequest.offset; 2078 let isPrepared: boolean = descriptorWriteRequest.isPrepared; 2079 let needRsp: boolean = descriptorWriteRequest.needRsp; 2080 let value: Uint8Array = new Uint8Array(descriptorWriteRequest.value); 2081 let descriptorUuid: string = descriptorWriteRequest.descriptorUuid; 2082 2083 descValue[0] = value[0]; 2084 let serverResponse: ble.ServerResponse = {deviceId: deviceId, transId: transId, status: 0, offset: offset, value:arrayBufferDesc}; 2085 2086 try { 2087 gattServer.sendResponse(serverResponse); 2088 } catch (err) { 2089 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 2090 } 2091} 2092gattServer.on('descriptorWrite', WriteDescriptorReq); 2093``` 2094 2095 2096### off('descriptorWrite') 2097 2098off(type: 'descriptorWrite', callback?: Callback<DescriptorWriteRequest>): void 2099 2100Unsubscribes from descriptor write request events. 2101 2102**Required permissions**: ohos.permission.ACCESS_BLUETOOTH 2103 2104**Atomic service API**: This API can be used in atomic services since API version 12. 2105 2106**System capability**: SystemCapability.Communication.Bluetooth.Core 2107 2108**Parameters** 2109 2110| Name | Type | Mandatory | Description | 2111| -------- | ---------------------------------------- | ---- | ---------------------------------------- | 2112| type | string | Yes | Event type. The value **descriptorWrite** indicates a descriptor write request event. | 2113| callback | Callback<[DescriptorWriteRequest](#descriptorwriterequest)> | No | Callback to unregister.<br>If this parameter is specified, it must be the same as the callback in [on('descriptorWrite')](#ondescriptorwrite). If this parameter is not specified, all callbacks corresponding to the event type are unsubscribed.| 2114 2115**Error codes** 2116 2117For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 2118 2119| ID| Error Message| 2120| -------- | ---------------------------- | 2121|201 | Permission denied. | 2122|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 2123|801 | Capability not supported. | 2124 2125**Example** 2126 2127```js 2128import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 2129try { 2130let gattServer: ble.GattServer = ble.createGattServer(); 2131gattServer.off('descriptorWrite'); 2132} catch (err) { 2133 console.error("errCode:" + (err as BusinessError).code + ",errMessage:" + (err as BusinessError).message); 2134} 2135``` 2136 2137 2138### on('connectionStateChange') 2139 2140on(type: 'connectionStateChange', callback: Callback<BLEConnectionChangeState>): void 2141 2142Subscribes to GATT connection state change events on the server. This API uses an asynchronous callback to return the result. 2143 2144**Required permissions**: ohos.permission.ACCESS_BLUETOOTH 2145 2146**Atomic service API**: This API can be used in atomic services since API version 12. 2147 2148**System capability**: SystemCapability.Communication.Bluetooth.Core 2149 2150**Parameters** 2151 2152| Name | Type | Mandatory | Description | 2153| -------- | ---------------------------------------- | ---- | ---------------------------------------- | 2154| type | string | Yes | Event type. The value **connectionStateChange** indicates a connection state change event.<br>This event is triggered when the GATT connection state changes.<br>For example, the connection status may change when a connection request or disconnection request is received.| 2155| callback | Callback<[BLEConnectionChangeState](#bleconnectionchangestate)> | Yes | Callback used to return the GATT connection state change event. | 2156 2157**Error codes** 2158 2159For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 2160 2161| ID| Error Message| 2162| -------- | ---------------------------- | 2163|201 | Permission denied. | 2164|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 2165|801 | Capability not supported. | 2166 2167**Example** 2168 2169```js 2170import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 2171let Connected = (bleConnectionChangeState: ble.BLEConnectionChangeState) => { 2172 let deviceId: string = bleConnectionChangeState.deviceId; 2173 let status: constant.ProfileConnectionState = bleConnectionChangeState.state; 2174} 2175try { 2176 let gattServer: ble.GattServer = ble.createGattServer(); 2177 gattServer.on('connectionStateChange', Connected); 2178} catch (err) { 2179 console.error("errCode:" + (err as BusinessError).code + ",errMessage:" + (err as BusinessError).message); 2180} 2181``` 2182 2183 2184### off('connectionStateChange') 2185 2186off(type: 'connectionStateChange', callback?: Callback<BLEConnectionChangeState>): void 2187 2188Unsubscribes from GATT connection state change events on the server. 2189 2190**Required permissions**: ohos.permission.ACCESS_BLUETOOTH 2191 2192**Atomic service API**: This API can be used in atomic services since API version 12. 2193 2194**System capability**: SystemCapability.Communication.Bluetooth.Core 2195 2196**Parameters** 2197 2198| Name | Type | Mandatory | Description | 2199| -------- | ---------------------------------------- | ---- | ---------------------------------------- | 2200| type | string | Yes | Event type. The value **connectionStateChange** indicates a connection state change event.| 2201| callback | Callback<[BLEConnectionChangeState](#bleconnectionchangestate)> | No | Callback to unregister.<br>If this parameter is specified, it must be the same as the callback in [on('connectionStateChange')](#onconnectionstatechange). If this parameter is not specified, all callbacks corresponding to the event type are unsubscribed.| 2202 2203**Error codes** 2204 2205For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 2206 2207| ID| Error Message| 2208| -------- | ---------------------------- | 2209|201 | Permission denied. | 2210|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 2211|801 | Capability not supported. | 2212 2213**Example** 2214 2215```js 2216import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 2217try { 2218 let gattServer: ble.GattServer = ble.createGattServer(); 2219 gattServer.off('connectionStateChange'); 2220} catch (err) { 2221 console.error("errCode:" + (err as BusinessError).code + ",errMessage:" + (err as BusinessError).message); 2222} 2223``` 2224 2225 2226### on('BLEMtuChange') 2227 2228on(type: 'BLEMtuChange', callback: Callback<number>): void 2229 2230Subscribes to MTU change events on the server. This API uses an asynchronous callback to return the result. 2231 2232**Required permissions**: ohos.permission.ACCESS_BLUETOOTH 2233 2234**System capability**: SystemCapability.Communication.Bluetooth.Core 2235 2236**Parameters** 2237 2238| Name | Type | Mandatory | Description | 2239| -------- | ---------------------------------------- | ---- | ---------------------------------------- | 2240| type | string | Yes | Event type. The value **BLEMtuChange** indicates an MTU change event.<br>This event is triggered when the client initiates an MTU negotiation request.| 2241| callback | Callback<number> | Yes | Callback used to return the negotiated MTU, in bytes.| 2242 2243**Error codes** 2244 2245For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 2246 2247| ID| Error Message| 2248| -------- | ---------------------------- | 2249|201 | Permission denied. | 2250|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 2251|801 | Capability not supported. | 2252 2253**Example** 2254 2255```js 2256import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 2257try { 2258 let gattServer: ble.GattServer = ble.createGattServer(); 2259 gattServer.on('BLEMtuChange', (mtu: number) => { 2260 console.info('BLEMtuChange, mtu: ' + mtu); 2261 }); 2262} catch (err) { 2263 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 2264} 2265``` 2266 2267 2268### off('BLEMtuChange') 2269 2270off(type: 'BLEMtuChange', callback?: Callback<number>): void 2271 2272Unsubscribes from MTU change events on the server. 2273 2274**Required permissions**: ohos.permission.ACCESS_BLUETOOTH 2275 2276**System capability**: SystemCapability.Communication.Bluetooth.Core 2277 2278**Parameters** 2279 2280| Name | Type | Mandatory | Description | 2281| -------- | ---------------------------------------- | ---- | ---------------------------------------- | 2282| type | string | Yes | Event type. The value **BLEMtuChange** indicates an MTU change event.| 2283| callback | Callback<number> | No | Callback to unregister.<br>If this parameter is specified, it must be the same as the callback in [on('BLEMtuChange')](#onblemtuchange). If this parameter is not specified, all callbacks corresponding to the event type are unsubscribed.| 2284 2285**Error codes** 2286 2287For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 2288 2289| ID| Error Message| 2290| -------- | ---------------------------- | 2291|201 | Permission denied. | 2292|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 2293|801 | Capability not supported. | 2294 2295**Example** 2296 2297```js 2298import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 2299try { 2300 let gattServer: ble.GattServer = ble.createGattServer(); 2301 gattServer.off('BLEMtuChange'); 2302} catch (err) { 2303 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 2304} 2305``` 2306 2307 2308## GattClientDevice 2309 2310Represents a GATT client class. It provides APIs for connecting to and transmitting data with the server. 2311 2312- Before using the APIs of this class, you need to call [createGattClientDevice](#blecreategattclientdevice) to construct a GATT client instance. 2313- You can create multiple instances of this class to manage multiple GATT connections. 2314 2315### connect 2316 2317connect(): void 2318 2319Initiates a GATT connection to the server. 2320 2321- The address of the peer device has been specified by the **deviceId** in [createGattClientDevice](#blecreategattclientdevice). 2322- The client can use [on('BLEConnectionStateChange')](#onbleconnectionstatechange) to subscribe to connection state change events. 2323 2324**Required permissions**: ohos.permission.ACCESS_BLUETOOTH 2325 2326**Atomic service API**: This API can be used in atomic services since API version 12. 2327 2328**System capability**: SystemCapability.Communication.Bluetooth.Core 2329 2330**Error codes** 2331 2332For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Bluetooth Error Codes](errorcode-bluetoothManager.md). 2333 2334| ID| Error Message| 2335| -------- | ---------------------------- | 2336|201 | Permission denied. | 2337|801 | Capability not supported. | 2338|2900001 | Service stopped. | 2339|2900003 | Bluetooth disabled. | 2340|2900099 | Operation failed. | 2341 2342**Example** 2343 2344```js 2345import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 2346try { 2347 let device: ble.GattClientDevice = ble.createGattClientDevice('XX:XX:XX:XX:XX:XX'); 2348 device.connect(); 2349} catch (err) { 2350 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 2351} 2352``` 2353 2354 2355### disconnect 2356 2357disconnect(): void 2358 2359Disconnects the GATT connection from the server. 2360 2361- The client can use [on('BLEConnectionStateChange')](#onbleconnectionstatechange) to subscribe to connection state change events. 2362 2363**Required permissions**: ohos.permission.ACCESS_BLUETOOTH 2364 2365**Atomic service API**: This API can be used in atomic services since API version 12. 2366 2367**System capability**: SystemCapability.Communication.Bluetooth.Core 2368 2369**Error codes** 2370 2371For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Bluetooth Error Codes](errorcode-bluetoothManager.md). 2372 2373| ID| Error Message| 2374| -------- | ---------------------------- | 2375|201 | Permission denied. | 2376|801 | Capability not supported. | 2377|2900001 | Service stopped. | 2378|2900003 | Bluetooth disabled. | 2379|2900099 | Operation failed. | 2380 2381**Example** 2382 2383```js 2384import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 2385try { 2386 let device: ble.GattClientDevice = ble.createGattClientDevice('XX:XX:XX:XX:XX:XX'); 2387 device.disconnect(); 2388} catch (err) { 2389 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 2390} 2391``` 2392 2393 2394### close 2395 2396close(): void 2397 2398Closes a client instance. The instance created by calling [GattClientDevice](#gattclientdevice) is unavailable after being closed. 2399 2400**Required permissions**: ohos.permission.ACCESS_BLUETOOTH 2401 2402**Atomic service API**: This API can be used in atomic services since API version 12. 2403 2404**System capability**: SystemCapability.Communication.Bluetooth.Core 2405 2406**Error codes** 2407 2408For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Bluetooth Error Codes](errorcode-bluetoothManager.md). 2409 2410| ID| Error Message| 2411| -------- | ---------------------------- | 2412|201 | Permission denied. | 2413|801 | Capability not supported. | 2414|2900001 | Service stopped. | 2415|2900003 | Bluetooth disabled. | 2416|2900099 | Operation failed. | 2417 2418**Example** 2419 2420```js 2421import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 2422try { 2423 let device: ble.GattClientDevice = ble.createGattClientDevice('XX:XX:XX:XX:XX:XX'); 2424 device.close(); 2425} catch (err) { 2426 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 2427} 2428``` 2429 2430 2431### getDeviceName 2432 2433getDeviceName(callback: AsyncCallback<string>): void 2434 2435Obtains the device name of the server. This API uses an asynchronous callback to return the result. 2436 2437**Required permissions**: ohos.permission.ACCESS_BLUETOOTH 2438 2439**Atomic service API**: This API can be used in atomic services since API version 12. 2440 2441**System capability**: SystemCapability.Communication.Bluetooth.Core 2442 2443**Parameters** 2444 2445| Name | Type | Mandatory | Description | 2446| -------- | --------------------------- | ---- | ------------------------------- | 2447| callback | AsyncCallback<string> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**, and **data** is the device name of the server.| 2448 2449**Error codes** 2450 2451For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Bluetooth Error Codes](errorcode-bluetoothManager.md). 2452 2453| ID| Error Message| 2454| -------- | ---------------------------- | 2455|201 | Permission denied. | 2456|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 2457|801 | Capability not supported. | 2458|2900001 | Service stopped. | 2459|2900099 | Operation failed. | 2460 2461**Example** 2462 2463```js 2464import { ble, constant } from '@kit.ConnectivityKit'; 2465import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 2466let gattClient: ble.GattClientDevice = ble.createGattClientDevice("11:22:33:44:55:66"); 2467function ConnectStateChanged(state: ble.BLEConnectionChangeState) { 2468 console.info('bluetooth connect state changed'); 2469 let connectState: ble.ProfileConnectionState = state.state; 2470 if (connectState == constant.ProfileConnectionState.STATE_CONNECTED) { 2471 gattClient.getDeviceName((err: BusinessError, data: string)=> { 2472 console.info('device name err ' + JSON.stringify(err)); 2473 console.info('device name' + JSON.stringify(data)); 2474 }) 2475 } 2476} 2477// callback 2478try { 2479 gattClient.connect(); 2480} catch (err) { 2481 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 2482} 2483``` 2484 2485 2486### getDeviceName 2487 2488getDeviceName(): Promise<string> 2489 2490Obtains the name of the peer BLE device. This API uses a promise to return the result. 2491 2492**Required permissions**: ohos.permission.ACCESS_BLUETOOTH 2493 2494**Atomic service API**: This API can be used in atomic services since API version 12. 2495 2496**System capability**: SystemCapability.Communication.Bluetooth.Core 2497 2498**Return value** 2499 2500| Type | Description | 2501| --------------------- | ---------------------------------- | 2502| Promise<string> | Promise used to return the device name.| 2503 2504**Error codes** 2505 2506For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Bluetooth Error Codes](errorcode-bluetoothManager.md). 2507 2508| ID| Error Message| 2509| -------- | ---------------------------- | 2510|201 | Permission denied. | 2511|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 2512|801 | Capability not supported. | 2513|2900001 | Service stopped. | 2514|2900099 | Operation failed. | 2515 2516**Example** 2517 2518```js 2519import { ble, constant } from '@kit.ConnectivityKit'; 2520import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 2521let gattClient: ble.GattClientDevice = ble.createGattClientDevice("11:22:33:44:55:66"); 2522gattClient.on('BLEConnectionStateChange', ConnectStateChanged); 2523function ConnectStateChanged(state: ble.BLEConnectionChangeState) { 2524 console.info('bluetooth connect state changed'); 2525 let connectState: ble.ProfileConnectionState = state.state; 2526 if (connectState == constant.ProfileConnectionState.STATE_CONNECTED) { 2527 gattClient.getDeviceName().then((data: string) => { 2528 console.info('device name' + JSON.stringify(data)); 2529 }) 2530 } 2531} 2532// promise 2533try { 2534 gattClient.connect(); 2535} catch (err) { 2536 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 2537} 2538``` 2539 2540 2541### getServices 2542 2543getServices(callback: AsyncCallback<Array<GattService>>): void 2544 2545Obtains the list of services supported by the server. This API uses an asynchronous callback to return the result. 2546 2547Before invoking characteristic or descriptor read and write APIs, call this API to obtain the services supported by the server and ensure that the services include the characteristics or descriptors to be operated. The related APIs include: 2548 2549- [readCharacteristicValue](#readcharacteristicvalue) 2550- [readDescriptorValue](#readdescriptorvalue) 2551- [writeCharacteristicValue](#writecharacteristicvalue) 2552- [writeDescriptorValue](#writedescriptorvalue) 2553- [setCharacteristicChangeNotification](#setcharacteristicchangenotification) 2554- [setCharacteristicChangeIndication](#setcharacteristicchangeindication) 2555 2556**Required permissions**: ohos.permission.ACCESS_BLUETOOTH 2557 2558**Atomic service API**: This API can be used in atomic services since API version 12. 2559 2560**System capability**: SystemCapability.Communication.Bluetooth.Core 2561 2562**Parameters** 2563 2564| Name | Type | Mandatory | Description | 2565| -------- | ---------------------------------------- | ---- | ------------------------ | 2566| callback | AsyncCallback<Array<[GattService](#gattservice)>> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**, and **data** is the list of services supported by the server.| 2567 2568**Error codes** 2569 2570For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Bluetooth Error Codes](errorcode-bluetoothManager.md). 2571 2572| ID| Error Message| 2573| -------- | ---------------------------- | 2574|201 | Permission denied. | 2575|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 2576|801 | Capability not supported. | 2577|2900001 | Service stopped. | 2578|2900099 | Operation failed. | 2579 2580**Example** 2581 2582```js 2583import { ble, constant } from '@kit.ConnectivityKit'; 2584import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 2585// Callback mode. 2586let getServices = (code: BusinessError, gattServices: Array<ble.GattService>) => { 2587 if (code && code.code != 0) { 2588 console.info('bluetooth code is ' + code.code); 2589 return; 2590 } 2591 let services: Array<ble.GattService> = gattServices; 2592 console.info('bluetooth services size is ', services.length); 2593 for (let i = 0; i < services.length; i++) { 2594 console.info('bluetooth serviceUuid is ' + services[i].serviceUuid); 2595 } 2596} 2597let device: ble.GattClientDevice = ble.createGattClientDevice("11:22:33:44:55:66"); 2598function ConnectStateChanged(state: ble.BLEConnectionChangeState) { 2599 console.info('bluetooth connect state changed'); 2600 let connectState: ble.ProfileConnectionState = state.state; 2601 if (connectState == constant.ProfileConnectionState.STATE_CONNECTED) { 2602 device.getServices(getServices); 2603 } 2604} 2605 2606try { 2607 device.connect(); 2608} catch (err) { 2609 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 2610} 2611``` 2612 2613 2614### getServices 2615 2616getServices(): Promise<Array<GattService>> 2617 2618Obtains all services of the peer BLE device. This API uses a promise to return the result. 2619 2620**Required permissions**: ohos.permission.ACCESS_BLUETOOTH 2621 2622**Atomic service API**: This API can be used in atomic services since API version 12. 2623 2624**System capability**: SystemCapability.Communication.Bluetooth.Core 2625 2626**Return value** 2627 2628| Type | Description | 2629| ---------------------------------------- | --------------------------- | 2630| Promise<Array<[GattService](#gattservice)>> | Promise used to return the list of services supported by the server.| 2631 2632**Error codes** 2633 2634For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Bluetooth Error Codes](errorcode-bluetoothManager.md). 2635 2636| ID| Error Message| 2637| -------- | ---------------------------- | 2638|201 | Permission denied. | 2639|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 2640|801 | Capability not supported. | 2641|2900001 | Service stopped. | 2642|2900099 | Operation failed. | 2643 2644**Example** 2645 2646```js 2647import { ble, constant } from '@kit.ConnectivityKit'; 2648import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 2649// Promise mode. 2650let device: ble.GattClientDevice = ble.createGattClientDevice("11:22:33:44:55:66"); 2651function ConnectStateChanged(state: ble.BLEConnectionChangeState) { 2652 console.info('bluetooth connect state changed'); 2653 let connectState: ble.ProfileConnectionState = state.state; 2654 if (connectState == constant.ProfileConnectionState.STATE_CONNECTED) { 2655 device.getServices().then((result: Array<ble.GattService>) => { 2656 console.info('getServices successfully:' + JSON.stringify(result)); 2657 }); 2658 } 2659} 2660try { 2661 device.connect(); 2662} catch (err) { 2663 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 2664} 2665``` 2666 2667 2668### readCharacteristicValue 2669 2670readCharacteristicValue(characteristic: BLECharacteristic, callback: AsyncCallback<BLECharacteristic>): void 2671 2672Reads the value of the specified characteristic. This API uses an asynchronous callback to return the result.<br> 2673- You need to call [getServices](#getservices) to obtain all services supported by the server, and ensure that the UUID of the specified characteristic is included. Otherwise, the read operation will fail.<br> 2674- You can call the following APIs only after receiving an asynchronous callback: [readCharacteristicValue](#readcharacteristicvalue), [readDescriptorValue](#readdescriptorvalue), [writeCharacteristicValue](#writecharacteristicvalue), [writeDescriptorValue](#writedescriptorvalue), [getRssiValue](#getrssivalue), [setCharacteristicChangeNotification](#setcharacteristicchangenotification), and [setCharacteristicChangeIndication](#setcharacteristicchangeindication). 2675 2676**Required permissions**: ohos.permission.ACCESS_BLUETOOTH 2677 2678**Atomic service API**: This API can be used in atomic services since API version 12. 2679 2680**System capability**: SystemCapability.Communication.Bluetooth.Core 2681 2682**Parameters** 2683 2684| Name | Type | Mandatory | Description | 2685| -------------- | ---------------------------------------- | ---- | ----------------------- | 2686| characteristic | [BLECharacteristic](#blecharacteristic) | Yes | Characteristic to read. | 2687| callback | AsyncCallback<[BLECharacteristic](#blecharacteristic)> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**, and **data** is the characteristic object containing the read data. Otherwise, **err** is an error object.| 2688 2689**Error codes** 2690 2691For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Bluetooth Error Codes](errorcode-bluetoothManager.md). 2692 2693| ID| Error Message| 2694| -------- | ---------------------------- | 2695|201 | Permission denied. | 2696|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 2697|801 | Capability not supported. | 2698|2900001 | Service stopped. | 2699|2900011 | The operation is busy. The last operation is not complete. | 2700|2900099 | Operation failed. | 2701|2901000 | Read forbidden. | 2702|2901003 | The connection is not established. | 2703|2901004 | The connection is congested. | 2704|2901005 | The connection is not encrypted. | 2705|2901006 | The connection is not authenticated. | 2706|2901007 | The connection is not authorized. | 2707 2708**Example** 2709 2710```js 2711import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 2712function readCcc(code: BusinessError, BLECharacteristic: ble.BLECharacteristic) { 2713 if (code.code != 0) { 2714 return; 2715 } 2716 console.info('bluetooth characteristic uuid: ' + BLECharacteristic.characteristicUuid); 2717 let value = new Uint8Array(BLECharacteristic.characteristicValue); 2718 console.info('bluetooth characteristic value: ' + value[0]); 2719} 2720 2721let descriptors: Array<ble.BLEDescriptor> = []; 2722let bufferDesc = new ArrayBuffer(2); 2723let descV = new Uint8Array(bufferDesc); 2724descV[0] = 0; // Use the Client Characteristic Configuration descriptor as an example. When bit 0 and bit 1 are both set to 0, the notification and indication functions are disabled. 2725let descriptor: ble.BLEDescriptor = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', 2726characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', 2727descriptorUuid: '00002902-0000-1000-8000-00805F9B34FB', descriptorValue: bufferDesc}; 2728descriptors[0] = descriptor; 2729 2730let bufferCCC = new ArrayBuffer(8); 2731let cccV = new Uint8Array(bufferCCC); 2732cccV[0] = 1; 2733let characteristic: ble.BLECharacteristic = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', 2734characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', 2735characteristicValue: bufferCCC, descriptors:descriptors}; 2736 2737try { 2738 let device: ble.GattClientDevice = ble.createGattClientDevice('XX:XX:XX:XX:XX:XX'); 2739 device.readCharacteristicValue(characteristic, readCcc); 2740} catch (err) { 2741 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 2742} 2743``` 2744 2745 2746### readCharacteristicValue 2747 2748readCharacteristicValue(characteristic: BLECharacteristic): Promise<BLECharacteristic> 2749 2750Reads the value of the specified characteristic. This API uses a promise to return the result.<br> 2751- You need to call [getServices](#getservices) to obtain all services supported by the server, and ensure that the UUID of the specified characteristic is included. Otherwise, the read operation will fail.<br> 2752- You can call the following APIs only after receiving an asynchronous callback: [readCharacteristicValue](#readcharacteristicvalue), [readDescriptorValue](#readdescriptorvalue), [writeCharacteristicValue](#writecharacteristicvalue), [writeDescriptorValue](#writedescriptorvalue), [getRssiValue](#getrssivalue), [setCharacteristicChangeNotification](#setcharacteristicchangenotification), and [setCharacteristicChangeIndication](#setcharacteristicchangeindication). 2753 2754**Required permissions**: ohos.permission.ACCESS_BLUETOOTH 2755 2756**Atomic service API**: This API can be used in atomic services since API version 12. 2757 2758**System capability**: SystemCapability.Communication.Bluetooth.Core 2759 2760**Parameters** 2761 2762| Name | Type | Mandatory | Description | 2763| -------------- | --------------------------------------- | ---- | -------- | 2764| characteristic | [BLECharacteristic](#blecharacteristic) | Yes | Characteristic to read.| 2765 2766**Return value** 2767 2768| Type | Description | 2769| ---------------------------------------- | -------------------------- | 2770| Promise<[BLECharacteristic](#blecharacteristic)> | Promise used to return the characteristic object containing the read data.| 2771 2772**Error codes** 2773 2774For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Bluetooth Error Codes](errorcode-bluetoothManager.md). 2775 2776| ID| Error Message| 2777| -------- | ---------------------------- | 2778|201 | Permission denied. | 2779|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 2780|801 | Capability not supported. | 2781|2900001 | Service stopped. | 2782|2900011 | The operation is busy. The last operation is not complete. | 2783|2900099 | Operation failed. | 2784|2901000 | Read forbidden. | 2785|2901003 | The connection is not established. | 2786|2901004 | The connection is congested. | 2787|2901005 | The connection is not encrypted. | 2788|2901006 | The connection is not authenticated. | 2789|2901007 | The connection is not authorized. | 2790 2791**Example** 2792 2793```js 2794import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 2795let descriptors: Array<ble.BLEDescriptor> = []; 2796let bufferDesc = new ArrayBuffer(2); 2797let descV = new Uint8Array(bufferDesc); 2798descV[0] = 0; // Use the Client Characteristic Configuration descriptor as an example. When bit 0 and bit 1 are both set to 0, the notification and indication functions are disabled. 2799let descriptor: ble.BLEDescriptor = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', 2800characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', 2801descriptorUuid: '00002902-0000-1000-8000-00805F9B34FB', descriptorValue: bufferDesc}; 2802descriptors[0] = descriptor; 2803 2804let bufferCCC = new ArrayBuffer(8); 2805let cccV = new Uint8Array(bufferCCC); 2806cccV[0] = 1; 2807let characteristic: ble.BLECharacteristic = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', 2808characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', 2809characteristicValue: bufferCCC, descriptors:descriptors}; 2810 2811try { 2812 let device: ble.GattClientDevice = ble.createGattClientDevice('XX:XX:XX:XX:XX:XX'); 2813 device.readCharacteristicValue(characteristic); 2814} catch (err) { 2815 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 2816} 2817``` 2818 2819 2820### readDescriptorValue 2821 2822readDescriptorValue(descriptor: BLEDescriptor, callback: AsyncCallback<BLEDescriptor>): void 2823 2824Reads data from the specified descriptor. This API uses an asynchronous callback to return the result.<br> 2825- You need to call [getServices](#getservices) to obtain all services supported by the server, and ensure that the UUID of the specified descriptor is included. Otherwise, the read operation will fail.<br> 2826- You can call the following APIs only after receiving an asynchronous callback: [readCharacteristicValue](#readcharacteristicvalue), [readDescriptorValue](#readdescriptorvalue), [writeCharacteristicValue](#writecharacteristicvalue), [writeDescriptorValue](#writedescriptorvalue), [getRssiValue](#getrssivalue), [setCharacteristicChangeNotification](#setcharacteristicchangenotification), and [setCharacteristicChangeIndication](#setcharacteristicchangeindication). 2827 2828**Required permissions**: ohos.permission.ACCESS_BLUETOOTH 2829 2830**Atomic service API**: This API can be used in atomic services since API version 12. 2831 2832**System capability**: SystemCapability.Communication.Bluetooth.Core 2833 2834**Parameters** 2835 2836| Name | Type | Mandatory | Description | 2837| ---------- | ---------------------------------------- | ---- | ----------------------- | 2838| descriptor | [BLEDescriptor](#bledescriptor) | Yes | Descriptor to read. | 2839| callback | AsyncCallback<[BLEDescriptor](#bledescriptor)> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**, and **data** is the descriptor object containing the read data. Otherwise, **err** is an error object.| 2840 2841**Error codes** 2842 2843For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Bluetooth Error Codes](errorcode-bluetoothManager.md). 2844 2845| ID| Error Message| 2846| -------- | ---------------------------- | 2847|201 | Permission denied. | 2848|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 2849|801 | Capability not supported. | 2850|2900001 | Service stopped. | 2851|2900011 | The operation is busy. The last operation is not complete. | 2852|2900099 | Operation failed. | 2853|2901000 | Read forbidden. | 2854|2901003 | The connection is not established. | 2855|2901004 | The connection is congested. | 2856|2901005 | The connection is not encrypted. | 2857|2901006 | The connection is not authenticated. | 2858|2901007 | The connection is not authorized. | 2859 2860**Example** 2861 2862```js 2863import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 2864function readDesc(code: BusinessError, BLEDescriptor: ble.BLEDescriptor) { 2865 if (code.code != 0) { 2866 return; 2867 } 2868 console.info('bluetooth descriptor uuid: ' + BLEDescriptor.descriptorUuid); 2869 let value = new Uint8Array(BLEDescriptor.descriptorValue); 2870 console.info('bluetooth descriptor value: ' + value[0]); 2871} 2872 2873let bufferDesc = new ArrayBuffer(2); 2874let descV = new Uint8Array(bufferDesc); 2875descV[0] = 0; // Use the Client Characteristic Configuration descriptor as an example. When bit 0 and bit 1 are both set to 0, the notification and indication functions are disabled. 2876let descriptor: ble.BLEDescriptor = { 2877 serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', 2878 characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', 2879 descriptorUuid: '00002902-0000-1000-8000-00805F9B34FB', 2880 descriptorValue: bufferDesc 2881}; 2882try { 2883 let device: ble.GattClientDevice = ble.createGattClientDevice('XX:XX:XX:XX:XX:XX'); 2884 device.readDescriptorValue(descriptor, readDesc); 2885} catch (err) { 2886 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 2887} 2888``` 2889 2890 2891### readDescriptorValue 2892 2893readDescriptorValue(descriptor: BLEDescriptor): Promise<BLEDescriptor> 2894 2895Reads data from the specified descriptor. This API uses a promise to return the result.<br> 2896- You need to call [getServices](#getservices) to obtain all services supported by the server, and ensure that the UUID of the specified descriptor is included. Otherwise, the read operation will fail.<br> 2897- You can call the following APIs only after receiving an asynchronous callback: [readCharacteristicValue](#readcharacteristicvalue), [readDescriptorValue](#readdescriptorvalue), [writeCharacteristicValue](#writecharacteristicvalue), [writeDescriptorValue](#writedescriptorvalue), [getRssiValue](#getrssivalue), [setCharacteristicChangeNotification](#setcharacteristicchangenotification), and [setCharacteristicChangeIndication](#setcharacteristicchangeindication). 2898 2899**Required permissions**: ohos.permission.ACCESS_BLUETOOTH 2900 2901**Atomic service API**: This API can be used in atomic services since API version 12. 2902 2903**System capability**: SystemCapability.Communication.Bluetooth.Core 2904 2905**Parameters** 2906 2907| Name | Type | Mandatory | Description | 2908| ---------- | ------------------------------- | ---- | -------- | 2909| descriptor | [BLEDescriptor](#bledescriptor) | Yes | Descriptor to read.| 2910 2911**Return value** 2912 2913| Type | Description | 2914| ---------------------------------------- | -------------------------- | 2915| Promise<[BLEDescriptor](#bledescriptor)> | Promise used to return the descriptor object containing the read data.| 2916 2917**Error codes** 2918 2919For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Bluetooth Error Codes](errorcode-bluetoothManager.md). 2920 2921| ID| Error Message| 2922| -------- | ---------------------------- | 2923|201 | Permission denied. | 2924|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 2925|801 | Capability not supported. | 2926|2900001 | Service stopped. | 2927|2900011 | The operation is busy. The last operation is not complete. | 2928|2900099 | Operation failed. | 2929|2901000 | Read forbidden. | 2930|2901003 | The connection is not established. | 2931|2901004 | The connection is congested. | 2932|2901005 | The connection is not encrypted. | 2933|2901006 | The connection is not authenticated. | 2934|2901007 | The connection is not authorized. | 2935 2936**Example** 2937 2938```js 2939import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 2940let bufferDesc = new ArrayBuffer(2); 2941let descV = new Uint8Array(bufferDesc); 2942descV[0] = 0; // Use the Client Characteristic Configuration descriptor as an example. When bit 0 and bit 1 are both set to 0, the notification and indication functions are disabled. 2943let descriptor: ble.BLEDescriptor = { 2944 serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', 2945 characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', 2946 descriptorUuid: '00002902-0000-1000-8000-00805F9B34FB', 2947 descriptorValue: bufferDesc 2948}; 2949try { 2950 let device: ble.GattClientDevice = ble.createGattClientDevice('XX:XX:XX:XX:XX:XX'); 2951 device.readDescriptorValue(descriptor); 2952} catch (err) { 2953 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 2954} 2955``` 2956 2957 2958### writeCharacteristicValue 2959 2960writeCharacteristicValue(characteristic: BLECharacteristic, writeType: GattWriteType, callback: AsyncCallback<void>): void 2961 2962Writes a value to the specified characteristic. This API uses an asynchronous callback to return the result.<br> 2963- You need to call [getServices](#getservices) to obtain all services supported by the server, and ensure that the UUID of the specified characteristic is included. Otherwise, the write operation will fail.<br> 2964- You can call the following APIs only after receiving an asynchronous callback: [readCharacteristicValue](#readcharacteristicvalue), [readDescriptorValue](#readdescriptorvalue), [writeCharacteristicValue](#writecharacteristicvalue), [writeDescriptorValue](#writedescriptorvalue), [getRssiValue](#getrssivalue), [setCharacteristicChangeNotification](#setcharacteristicchangenotification), and [setCharacteristicChangeIndication](#setcharacteristicchangeindication). 2965 2966**Required permissions**: ohos.permission.ACCESS_BLUETOOTH 2967 2968**Atomic service API**: This API can be used in atomic services since API version 12. 2969 2970**System capability**: SystemCapability.Communication.Bluetooth.Core 2971 2972**Parameters** 2973 2974| Name | Type | Mandatory | Description | 2975| -------------- | --------------------------------------- | ---- | ------------------- | 2976| characteristic | [BLECharacteristic](#blecharacteristic) | Yes | Characteristic to write.| 2977| writeType | [GattWriteType](#gattwritetype) | Yes | Write mode.| 2978| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the write operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| 2979 2980**Error codes** 2981 2982For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Bluetooth Error Codes](errorcode-bluetoothManager.md). 2983 2984| ID| Error Message| 2985| -------- | ---------------------------- | 2986|201 | Permission denied. | 2987|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 2988|801 | Capability not supported. | 2989|2900001 | Service stopped. | 2990|2900011 | The operation is busy. The last operation is not complete. | 2991|2900099 | Operation failed. | 2992|2901001 | Write forbidden. | 2993|2901003 | The connection is not established. | 2994|2901004 | The connection is congested. | 2995|2901005 | The connection is not encrypted. | 2996|2901006 | The connection is not authenticated. | 2997|2901007 | The connection is not authorized. | 2998 2999**Example** 3000 3001```js 3002import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 3003let descriptors: Array<ble.BLEDescriptor> = []; 3004let bufferDesc = new ArrayBuffer(2); 3005let descV = new Uint8Array(bufferDesc); 3006descV[0] = 0; // Use the Client Characteristic Configuration descriptor as an example. When bit 0 and bit 1 are both set to 0, the notification and indication functions are disabled. 3007let descriptor: ble.BLEDescriptor = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', 3008 characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', 3009 descriptorUuid: '00002902-0000-1000-8000-00805F9B34FB', descriptorValue: bufferDesc}; 3010descriptors[0] = descriptor; 3011 3012let bufferCCC = new ArrayBuffer(8); 3013let cccV = new Uint8Array(bufferCCC); 3014cccV[0] = 1; 3015let characteristic: ble.BLECharacteristic = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', 3016 characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', 3017 characteristicValue: bufferCCC, descriptors:descriptors}; 3018function writeCharacteristicValueCallBack(code: BusinessError) { 3019 if (code != null) { 3020 return; 3021 } 3022 console.info('bluetooth writeCharacteristicValue success'); 3023} 3024try { 3025 let device: ble.GattClientDevice = ble.createGattClientDevice('XX:XX:XX:XX:XX:XX'); 3026 device.writeCharacteristicValue(characteristic, ble.GattWriteType.WRITE, writeCharacteristicValueCallBack); 3027} catch (err) { 3028 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 3029} 3030``` 3031 3032 3033### writeCharacteristicValue 3034 3035writeCharacteristicValue(characteristic: BLECharacteristic, writeType: GattWriteType): Promise<void> 3036 3037Writes a value to the specified characteristic. This API uses a promise to return the result.<br> 3038- You need to call [getServices](#getservices) to obtain all services supported by the server, and ensure that the UUID of the specified characteristic is included. Otherwise, the write operation will fail.<br> 3039- You can call the following APIs only after receiving an asynchronous callback: [readCharacteristicValue](#readcharacteristicvalue), [readDescriptorValue](#readdescriptorvalue), [writeCharacteristicValue](#writecharacteristicvalue), [writeDescriptorValue](#writedescriptorvalue), [getRssiValue](#getrssivalue), [setCharacteristicChangeNotification](#setcharacteristicchangenotification), and [setCharacteristicChangeIndication](#setcharacteristicchangeindication). 3040 3041**Required permissions**: ohos.permission.ACCESS_BLUETOOTH 3042 3043**Atomic service API**: This API can be used in atomic services since API version 12. 3044 3045**System capability**: SystemCapability.Communication.Bluetooth.Core 3046 3047**Parameters** 3048 3049| Name | Type | Mandatory | Description | 3050| -------------- | --------------------------------------- | ---- | ------------------- | 3051| characteristic | [BLECharacteristic](#blecharacteristic) | Yes | Characteristic to write.| 3052| writeType | [GattWriteType](#gattwritetype) | Yes | Write mode.| 3053 3054**Return value** 3055 3056| Type | Description | 3057| ---------------------------------------- | -------------------------- | 3058| Promise<void> | Promise that returns no value.| 3059 3060**Error codes** 3061 3062For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Bluetooth Error Codes](errorcode-bluetoothManager.md). 3063 3064| ID| Error Message| 3065| -------- | ---------------------------- | 3066|201 | Permission denied. | 3067|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 3068|801 | Capability not supported. | 3069|2900001 | Service stopped. | 3070|2900011 | The operation is busy. The last operation is not complete. | 3071|2900099 | Operation failed. | 3072|2901001 | Write forbidden. | 3073|2901003 | The connection is not established. | 3074|2901004 | The connection is congested. | 3075|2901005 | The connection is not encrypted. | 3076|2901006 | The connection is not authenticated. | 3077|2901007 | The connection is not authorized. | 3078 3079**Example** 3080 3081```js 3082import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 3083let descriptors: Array<ble.BLEDescriptor> = []; 3084let bufferDesc = new ArrayBuffer(2); 3085let descV = new Uint8Array(bufferDesc); 3086descV[0] = 0; // Use the Client Characteristic Configuration descriptor as an example. When bit 0 and bit 1 are both set to 0, the notification and indication functions are disabled. 3087let descriptor: ble.BLEDescriptor = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', 3088 characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', 3089 descriptorUuid: '00002902-0000-1000-8000-00805F9B34FB', descriptorValue: bufferDesc}; 3090descriptors[0] = descriptor; 3091 3092let bufferCCC = new ArrayBuffer(8); 3093let cccV = new Uint8Array(bufferCCC); 3094cccV[0] = 1; 3095let characteristic: ble.BLECharacteristic = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', 3096 characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', 3097 characteristicValue: bufferCCC, descriptors:descriptors}; 3098try { 3099 let device: ble.GattClientDevice = ble.createGattClientDevice('XX:XX:XX:XX:XX:XX'); 3100 device.writeCharacteristicValue(characteristic, ble.GattWriteType.WRITE); 3101} catch (err) { 3102 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 3103} 3104``` 3105 3106 3107### writeDescriptorValue 3108 3109writeDescriptorValue(descriptor: BLEDescriptor, callback: AsyncCallback<void>): void 3110 3111Writes data to the specified descriptor. This API uses an asynchronous callback to return the result.<br> 3112- You need to call [getServices](#getservices) to obtain all services supported by the server, and ensure that the UUID of the specified descriptor is included. Otherwise, the write operation will fail.<br> 3113- You can call the following APIs only after receiving an asynchronous callback: [readCharacteristicValue](#readcharacteristicvalue), [readDescriptorValue](#readdescriptorvalue), [writeCharacteristicValue](#writecharacteristicvalue), [writeDescriptorValue](#writedescriptorvalue), [getRssiValue](#getrssivalue), [setCharacteristicChangeNotification](#setcharacteristicchangenotification), and [setCharacteristicChangeIndication](#setcharacteristicchangeindication). 3114 3115**Required permissions**: ohos.permission.ACCESS_BLUETOOTH 3116 3117**Atomic service API**: This API can be used in atomic services since API version 12. 3118 3119**System capability**: SystemCapability.Communication.Bluetooth.Core 3120 3121**Parameters** 3122 3123| Name | Type | Mandatory | Description | 3124| ---------- | ------------------------------- | ---- | ------------------ | 3125| descriptor | [BLEDescriptor](#bledescriptor) | Yes | Descriptor to write.| 3126| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the write operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| 3127 3128**Error codes** 3129 3130For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Bluetooth Error Codes](errorcode-bluetoothManager.md). 3131 3132| ID| Error Message| 3133| -------- | ---------------------------- | 3134|201 | Permission denied. | 3135|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 3136|801 | Capability not supported. | 3137|2900001 | Service stopped. | 3138|2900011 | The operation is busy. The last operation is not complete. | 3139|2900099 | Operation failed. | 3140|2901001 | Write forbidden. | 3141|2901003 | The connection is not established. | 3142|2901004 | The connection is congested. | 3143|2901005 | The connection is not encrypted. | 3144|2901006 | The connection is not authenticated. | 3145|2901007 | The connection is not authorized. | 3146 3147**Example** 3148 3149```js 3150import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 3151let bufferDesc = new ArrayBuffer(2); 3152let descV = new Uint8Array(bufferDesc); 3153descV[0] = 0; // Use the Client Characteristic Configuration descriptor as an example. When bit 0 and bit 1 are both set to 0, the notification and indication functions are disabled. 3154let descriptor: ble.BLEDescriptor = { 3155 serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', 3156 characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', 3157 descriptorUuid: '00002902-0000-1000-8000-00805F9B34FB', 3158 descriptorValue: bufferDesc 3159}; 3160try { 3161 let device: ble.GattClientDevice = ble.createGattClientDevice('XX:XX:XX:XX:XX:XX'); 3162 device.writeDescriptorValue(descriptor, (err: BusinessError) => { 3163 if (err) { 3164 console.error('writeDescriptorValue callback failed'); 3165 } else { 3166 console.info('writeDescriptorValue callback successful'); 3167 } 3168 }); 3169} catch (err) { 3170 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 3171} 3172``` 3173 3174 3175### writeDescriptorValue 3176 3177writeDescriptorValue(descriptor: BLEDescriptor): Promise<void> 3178 3179Writes data to the specified descriptor. This API uses a promise to return the result.<br> 3180- You need to call [getServices](#getservices) to obtain all services supported by the server, and ensure that the UUID of the specified descriptor is included. Otherwise, the write operation will fail.<br> 3181- You can call the following APIs only after receiving an asynchronous callback: [readCharacteristicValue](#readcharacteristicvalue), [readDescriptorValue](#readdescriptorvalue), [writeCharacteristicValue](#writecharacteristicvalue), [writeDescriptorValue](#writedescriptorvalue), [getRssiValue](#getrssivalue), [setCharacteristicChangeNotification](#setcharacteristicchangenotification), and [setCharacteristicChangeIndication](#setcharacteristicchangeindication). 3182 3183**Required permissions**: ohos.permission.ACCESS_BLUETOOTH 3184 3185**Atomic service API**: This API can be used in atomic services since API version 12. 3186 3187**System capability**: SystemCapability.Communication.Bluetooth.Core 3188 3189**Parameters** 3190 3191| Name | Type | Mandatory | Description | 3192| ---------- | ------------------------------- | ---- | ------------------ | 3193| descriptor | [BLEDescriptor](#bledescriptor) | Yes | Descriptor to write.| 3194 3195**Return value** 3196 3197| Type | Description | 3198| ---------------------------------------- | -------------------------- | 3199| Promise<void> | Promise that returns no value.| 3200 3201**Error codes** 3202 3203For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Bluetooth Error Codes](errorcode-bluetoothManager.md). 3204 3205| ID| Error Message| 3206| -------- | ---------------------------- | 3207|201 | Permission denied. | 3208|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 3209|801 | Capability not supported. | 3210|2900001 | Service stopped. | 3211|2900011 | The operation is busy. The last operation is not complete. | 3212|2900099 | Operation failed. | 3213|2901001 | Write forbidden. | 3214|2901003 | The connection is not established. | 3215|2901004 | The connection is congested. | 3216|2901005 | The connection is not encrypted. | 3217|2901006 | The connection is not authenticated. | 3218|2901007 | The connection is not authorized. | 3219 3220**Example** 3221 3222```js 3223import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 3224let bufferDesc = new ArrayBuffer(2); 3225let descV = new Uint8Array(bufferDesc); 3226descV[0] = 0; // Use the Client Characteristic Configuration descriptor as an example. When bit 0 and bit 1 are both set to 0, the notification and indication functions are disabled. 3227let descriptor: ble.BLEDescriptor = { 3228 serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', 3229 characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', 3230 descriptorUuid: '00002902-0000-1000-8000-00805F9B34FB', 3231 descriptorValue: bufferDesc 3232}; 3233try { 3234 let device: ble.GattClientDevice = ble.createGattClientDevice('XX:XX:XX:XX:XX:XX'); 3235 device.writeDescriptorValue(descriptor).then(() => { 3236 console.info('writeDescriptorValue promise success'); 3237 }); 3238} catch (err) { 3239 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 3240} 3241``` 3242 3243 3244### getRssiValue 3245 3246getRssiValue(callback: AsyncCallback<number>): void 3247 3248Obtains the RSSI of a GATT connection. This API uses an asynchronous callback to return the result.<br> 3249- You can call this API only after the GATT profile is connected by calling [connect](#connect). 3250- You can call the following APIs only after receiving an asynchronous callback: [readCharacteristicValue](#readcharacteristicvalue), [readDescriptorValue](#readdescriptorvalue), [writeCharacteristicValue](#writecharacteristicvalue), [writeDescriptorValue](#writedescriptorvalue), [getRssiValue](#getrssivalue), [setCharacteristicChangeNotification](#setcharacteristicchangenotification), and [setCharacteristicChangeIndication](#setcharacteristicchangeindication). 3251 3252**Required permissions**: ohos.permission.ACCESS_BLUETOOTH 3253 3254**Atomic service API**: This API can be used in atomic services since API version 12. 3255 3256**System capability**: SystemCapability.Communication.Bluetooth.Core 3257 3258**Parameters** 3259 3260| Name | Type | Mandatory | Description | 3261| -------- | --------------------------- | ---- | ------------------------------ | 3262| callback | AsyncCallback<number> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**, and **data** is the obtained RSSI (unit: dBm). Otherwise, **err** is an error object.| 3263 3264**Error codes** 3265 3266For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Bluetooth Error Codes](errorcode-bluetoothManager.md). 3267 3268| ID| Error Message| 3269| -------- | ---------------------------- | 3270|201 | Permission denied. | 3271|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 3272|801 | Capability not supported. | 3273|2900011 | The operation is busy. The last operation is not complete. | 3274|2900099 | Operation failed. | 3275|2901003 | The connection is not established. | 3276 3277**Example** 3278 3279```js 3280import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 3281// callback 3282try { 3283 let gattClient: ble.GattClientDevice = ble.createGattClientDevice("XX:XX:XX:XX:XX:XX"); 3284 gattClient.connect(); 3285 let rssi = gattClient.getRssiValue((err: BusinessError, data: number)=> { 3286 console.info('rssi err ' + JSON.stringify(err)); 3287 console.info('rssi value' + JSON.stringify(data)); 3288 }) 3289} catch (err) { 3290 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 3291} 3292``` 3293 3294 3295### getRssiValue 3296 3297getRssiValue(): Promise<number> 3298 3299Obtains the RSSI of a GATT connection. This API uses a promise to return the result.<br> 3300- You can call this API only after the GATT profile is connected by calling [connect](#connect). 3301- You can call the following APIs only after receiving an asynchronous callback: [readCharacteristicValue](#readcharacteristicvalue), [readDescriptorValue](#readdescriptorvalue), [writeCharacteristicValue](#writecharacteristicvalue), [writeDescriptorValue](#writedescriptorvalue), [getRssiValue](#getrssivalue), [setCharacteristicChangeNotification](#setcharacteristicchangenotification), and [setCharacteristicChangeIndication](#setcharacteristicchangeindication). 3302 3303**Required permissions**: ohos.permission.ACCESS_BLUETOOTH 3304 3305**Atomic service API**: This API can be used in atomic services since API version 12. 3306 3307**System capability**: SystemCapability.Communication.Bluetooth.Core 3308 3309**Return value** 3310 3311| Type | Description | 3312| --------------------- | --------------------------------- | 3313| Promise<number> | Promise used to return the result. used to return the signal strength, in dBm.| 3314 3315**Error codes** 3316 3317For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Bluetooth Error Codes](errorcode-bluetoothManager.md). 3318 3319| ID| Error Message| 3320| -------- | ---------------------------- | 3321|201 | Permission denied. | 3322|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 3323|801 | Capability not supported. | 3324|2900011 | The operation is busy. The last operation is not complete. | 3325|2900099 | Operation failed. | 3326|2901003 | The connection is not established. | 3327 3328**Example** 3329 3330```js 3331import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 3332// promise 3333try { 3334 let gattClient: ble.GattClientDevice = ble.createGattClientDevice("XX:XX:XX:XX:XX:XX"); 3335 gattClient.getRssiValue().then((data: number) => { 3336 console.info('rssi' + JSON.stringify(data)); 3337 }) 3338} catch (err) { 3339 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 3340} 3341``` 3342 3343 3344### setBLEMtuSize 3345 3346setBLEMtuSize(mtu: number): void 3347 3348Negotiates the MTU between the client and server.<br> 3349- You can call this API only after the GATT profile is connected by calling [connect](#connect).<br> 3350- You can call [on('BLEMtuChange')](#onblemtuchange-1) to subscribe to the MTU negotiation result. 3351 3352**Required permissions**: ohos.permission.ACCESS_BLUETOOTH 3353 3354**Atomic service API**: This API can be used in atomic services since API version 12. 3355 3356**System capability**: SystemCapability.Communication.Bluetooth.Core 3357 3358**Parameters** 3359 3360| Name | Type | Mandatory | Description | 3361| ---- | ------ | ---- | -------------- | 3362| mtu | number | Yes | MTU to negotiate. The value range is [23, 517], in bytes.| 3363 3364**Error codes** 3365 3366For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Bluetooth Error Codes](errorcode-bluetoothManager.md). 3367 3368| ID| Error Message| 3369| -------- | ---------------------------- | 3370|201 | Permission denied. | 3371|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 3372|801 | Capability not supported. | 3373|2900001 | Service stopped. | 3374|2900099 | Operation failed. | 3375 3376**Example** 3377 3378```js 3379import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 3380try { 3381 let device: ble.GattClientDevice = ble.createGattClientDevice('XX:XX:XX:XX:XX:XX'); 3382 device.setBLEMtuSize(128); 3383} catch (err) { 3384 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 3385} 3386``` 3387 3388 3389### setCharacteristicChangeNotification 3390 3391setCharacteristicChangeNotification(characteristic: BLECharacteristic, enable: boolean, callback: AsyncCallback<void>): void 3392 3393Sets whether to enable the client to receive characteristic change notifications from the server. This API uses an asynchronous callback to return the result.<br> 3394- You need to call [getServices](#getservices) to obtain all services supported by the server, and ensure that the UUID of the specified characteristic is included.<br> 3395- The server can send change notifications only if the specified characteristic contains the UUID (00002902-0000-1000-8000-00805f9b34fb) of the Client Characteristic Configuration descriptor.<br> 3396- If **enable** is set to **true**, the system Bluetooth service automatically writes the Client Characteristic Configuration descriptor to the server to enable the change notification function.<br> 3397- If **enable** is set to **false**, the system Bluetooth service automatically writes the Client Characteristic Configuration descriptor to the server to disable the change notification function.<br> 3398- You can call [on('BLECharacteristicChange')](#onblecharacteristicchange) to subscribe to characteristic change notifications of the server.<br> 3399- The client does not need to send a response when receiving a characteristic change notification from the server. 3400- You can call the following APIs only after receiving an asynchronous callback: [readCharacteristicValue](#readcharacteristicvalue), [readDescriptorValue](#readdescriptorvalue), [writeCharacteristicValue](#writecharacteristicvalue), [writeDescriptorValue](#writedescriptorvalue), [getRssiValue](#getrssivalue), [setCharacteristicChangeNotification](#setcharacteristicchangenotification), and [setCharacteristicChangeIndication](#setcharacteristicchangeindication). 3401 3402**Required permissions**: ohos.permission.ACCESS_BLUETOOTH 3403 3404**Atomic service API**: This API can be used in atomic services since API version 12. 3405 3406**System capability**: SystemCapability.Communication.Bluetooth.Core 3407 3408**Parameters** 3409 3410| Name | Type | Mandatory | Description | 3411| -------------- | --------------------------------------- | ---- | ----------------------------- | 3412| characteristic | [BLECharacteristic](#blecharacteristic) | Yes | Characteristic of the server. | 3413| enable | boolean | Yes | Whether to enable characteristic change notification.<br>The value **true** means to enable the application, and **false** means the opposite.| 3414| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| 3415 3416**Error codes** 3417 3418For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Bluetooth Error Codes](errorcode-bluetoothManager.md). 3419 3420| ID| Error Message| 3421| -------- | ---------------------------- | 3422|201 | Permission denied. | 3423|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 3424|801 | Capability not supported. | 3425|2900001 | Service stopped. | 3426|2900011 | The operation is busy. The last operation is not complete. | 3427|2900099 | Operation failed. | 3428|2901003 | The connection is not established. | 3429 3430**Example** 3431 3432```js 3433import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 3434// Create descriptors. 3435let descriptors: Array<ble.BLEDescriptor> = []; 3436let arrayBuffer = new ArrayBuffer(2); 3437let descV = new Uint8Array(arrayBuffer); 3438descV[0] = 0; // Use the Client Characteristic Configuration descriptor as an example. When bit 0 and bit 1 are both set to 0, the notification and indication functions are disabled. 3439let descriptor: ble.BLEDescriptor = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', 3440 characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', 3441 descriptorUuid: '00002902-0000-1000-8000-00805F9B34FB', descriptorValue: arrayBuffer}; 3442descriptors[0] = descriptor; 3443let arrayBufferC = new ArrayBuffer(8); 3444let characteristic: ble.BLECharacteristic = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', 3445 characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', characteristicValue: arrayBufferC, descriptors:descriptors}; 3446try { 3447 let device: ble.GattClientDevice = ble.createGattClientDevice('XX:XX:XX:XX:XX:XX'); 3448 device.setCharacteristicChangeNotification(characteristic, false, (err: BusinessError) => { 3449 if (err) { 3450 console.error('notifyCharacteristicChanged callback failed'); 3451 } else { 3452 console.info('notifyCharacteristicChanged callback successful'); 3453 } 3454 }); 3455} catch (err) { 3456 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 3457} 3458 3459``` 3460 3461 3462### setCharacteristicChangeNotification 3463 3464setCharacteristicChangeNotification(characteristic: BLECharacteristic, enable: boolean): Promise<void> 3465 3466Sets whether to enable the client to receive characteristic change notifications from the server. This API uses a promise to return the result.<br> 3467- You need to call [getServices](#getservices) to obtain all services supported by the server, and ensure that the UUID of the specified characteristic is included.<br> 3468- The server can send change notifications only if the specified characteristic contains the UUID (00002902-0000-1000-8000-00805f9b34fb) of the Client Characteristic Configuration descriptor.<br> 3469- If **enable** is set to **true**, the system Bluetooth service automatically writes the Client Characteristic Configuration descriptor to the server to enable the change notification function.<br> 3470- If **enable** is set to **false**, the system Bluetooth service automatically writes the Client Characteristic Configuration descriptor to the server to disable the change notification function.<br> 3471- You can call [on('BLECharacteristicChange')](#onblecharacteristicchange) to subscribe to characteristic change notifications of the server.<br> 3472- The client does not need to send a response when receiving a characteristic change notification from the server. 3473- You can call the following APIs only after receiving an asynchronous callback: [readCharacteristicValue](#readcharacteristicvalue), [readDescriptorValue](#readdescriptorvalue), [writeCharacteristicValue](#writecharacteristicvalue), [writeDescriptorValue](#writedescriptorvalue), [getRssiValue](#getrssivalue), [setCharacteristicChangeNotification](#setcharacteristicchangenotification), and [setCharacteristicChangeIndication](#setcharacteristicchangeindication). 3474 3475**Required permissions**: ohos.permission.ACCESS_BLUETOOTH 3476 3477**Atomic service API**: This API can be used in atomic services since API version 12. 3478 3479**System capability**: SystemCapability.Communication.Bluetooth.Core 3480 3481**Parameters** 3482 3483| Name | Type | Mandatory | Description | 3484| -------------- | --------------------------------------- | ---- | ----------------------------- | 3485| characteristic | [BLECharacteristic](#blecharacteristic) | Yes | Characteristic of the server. | 3486| enable | boolean | Yes | Whether to enable characteristic change notification.<br>**true** to enable, **false** otherwise.| 3487 3488**Return value** 3489 3490| Type | Description | 3491| ---------------------------------------- | -------------------------- | 3492| Promise<void> | Promise that returns no value.| 3493 3494**Error codes** 3495 3496For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Bluetooth Error Codes](errorcode-bluetoothManager.md). 3497 3498| ID| Error Message| 3499| -------- | ---------------------------- | 3500|201 | Permission denied. | 3501|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 3502|801 | Capability not supported. | 3503|2900001 | Service stopped. | 3504|2900011 | The operation is busy. The last operation is not complete. | 3505|2900099 | Operation failed. | 3506|2901003 | The connection is not established. | 3507 3508**Example** 3509 3510```js 3511import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 3512// Create descriptors. 3513let descriptors: Array<ble.BLEDescriptor> = []; 3514let arrayBuffer = new ArrayBuffer(2); 3515let descV = new Uint8Array(arrayBuffer); 3516descV[0] = 0; // Use the Client Characteristic Configuration descriptor as an example. When bit 0 and bit 1 are both set to 0, the notification and indication functions are disabled. 3517let descriptor: ble.BLEDescriptor = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', 3518 characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', 3519 descriptorUuid: '00002902-0000-1000-8000-00805F9B34FB', descriptorValue: arrayBuffer}; 3520descriptors[0] = descriptor; 3521let arrayBufferC = new ArrayBuffer(8); 3522let characteristic: ble.BLECharacteristic = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', 3523 characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', characteristicValue: arrayBufferC, descriptors:descriptors}; 3524try { 3525 let device: ble.GattClientDevice = ble.createGattClientDevice('XX:XX:XX:XX:XX:XX'); 3526 device.setCharacteristicChangeNotification(characteristic, false); 3527} catch (err) { 3528 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 3529} 3530 3531``` 3532 3533 3534### setCharacteristicChangeIndication 3535 3536setCharacteristicChangeIndication(characteristic: BLECharacteristic, enable: boolean, callback: AsyncCallback<void>): void 3537 3538Sets whether to enable the client to receive characteristic change indications from the server. This API uses an asynchronous callback to return the result.<br> 3539- You need to call [getServices](#getservices) to obtain all services supported by the server, and ensure that the UUID of the specified characteristic is included.<br> 3540- The server can send change indications only if the specified characteristic contains the UUID (00002902-0000-1000-8000-00805f9b34fb) of the Client Characteristic Configuration descriptor.<br> 3541- If **enable** is set to **true**, the system Bluetooth service automatically writes the Client Characteristic Configuration descriptor to the server to enable the change indication function.<br> 3542- If **enable** is set to **false**, the system Bluetooth service automatically writes the Client Characteristic Configuration descriptor to the server to disable the change indication function.<br> 3543- You can call [on('BLECharacteristicChange')](#onblecharacteristicchange) to subscribe to characteristic change indications of the server.<br> 3544- When receiving a characteristic change indication from the server, the client does not need to send a response as this will be done by the Bluetooth service. 3545- You can call the following APIs only after receiving an asynchronous callback: [readCharacteristicValue](#readcharacteristicvalue), [readDescriptorValue](#readdescriptorvalue), [writeCharacteristicValue](#writecharacteristicvalue), [writeDescriptorValue](#writedescriptorvalue), [getRssiValue](#getrssivalue), [setCharacteristicChangeNotification](#setcharacteristicchangenotification), and [setCharacteristicChangeIndication](#setcharacteristicchangeindication). 3546 3547**Required permissions**: ohos.permission.ACCESS_BLUETOOTH 3548 3549**Atomic service API**: This API can be used in atomic services since API version 12. 3550 3551**System capability**: SystemCapability.Communication.Bluetooth.Core 3552 3553**Parameters** 3554 3555| Name | Type | Mandatory | Description | 3556| -------------- | --------------------------------------- | ---- | ----------------------------- | 3557| characteristic | [BLECharacteristic](#blecharacteristic) | Yes | Characteristic of the server. | 3558| enable | boolean | Yes | Whether to enable characteristic change indication.<br>The value **true** means to enable the application, and **false** means the opposite.| 3559| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| 3560 3561**Error codes** 3562 3563For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Bluetooth Error Codes](errorcode-bluetoothManager.md). 3564 3565| ID| Error Message| 3566| -------- | ---------------------------- | 3567|201 | Permission denied. | 3568|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 3569|801 | Capability not supported. | 3570|2900001 | Service stopped. | 3571|2900011 | The operation is busy. The last operation is not complete. | 3572|2900099 | Operation failed. | 3573|2901003 | The connection is not established. | 3574 3575**Example** 3576 3577```js 3578import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 3579// Create descriptors. 3580let descriptors: Array<ble.BLEDescriptor> = []; 3581let arrayBuffer = new ArrayBuffer(2); 3582let descV = new Uint8Array(arrayBuffer); 3583descV[0] = 0; // Use the Client Characteristic Configuration descriptor as an example. When bit 0 and bit 1 are both set to 0, the notification and indication functions are disabled. 3584let descriptor: ble.BLEDescriptor = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', 3585 characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', 3586 descriptorUuid: '00002902-0000-1000-8000-00805F9B34FB', descriptorValue: arrayBuffer}; 3587descriptors[0] = descriptor; 3588let arrayBufferC = new ArrayBuffer(8); 3589let characteristic: ble.BLECharacteristic = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', 3590 characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', characteristicValue: arrayBufferC, descriptors:descriptors}; 3591try { 3592 let device: ble.GattClientDevice = ble.createGattClientDevice('XX:XX:XX:XX:XX:XX'); 3593 device.setCharacteristicChangeIndication(characteristic, false, (err: BusinessError) => { 3594 if (err) { 3595 console.error('notifyCharacteristicChanged callback failed'); 3596 } else { 3597 console.info('notifyCharacteristicChanged callback successful'); 3598 } 3599 }); 3600} catch (err) { 3601 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 3602} 3603 3604``` 3605 3606 3607### setCharacteristicChangeIndication 3608 3609setCharacteristicChangeIndication(characteristic: BLECharacteristic, enable: boolean): Promise<void> 3610 3611Sets whether to enable the client to receive characteristic change indications from the server. This API uses an asynchronous callback to return the result.<br> 3612- You need to call [getServices](#getservices) to obtain all services supported by the server, and ensure that the UUID of the specified characteristic is included.<br> 3613- The server can send change indications only if the specified characteristic contains the UUID (00002902-0000-1000-8000-00805f9b34fb) of the Client Characteristic Configuration descriptor.<br> 3614- If **enable** is set to **true**, the system Bluetooth service automatically writes the Client Characteristic Configuration descriptor to the server to enable the change indication function.<br> 3615- If **enable** is set to **false**, the system Bluetooth service automatically writes the Client Characteristic Configuration descriptor to the server to disable the change indication function.<br> 3616- You can call [on('BLECharacteristicChange')](#onblecharacteristicchange) to subscribe to characteristic change indications of the server.<br> 3617- When receiving a characteristic change indication from the server, the client does not need to send a response as this will be done by the Bluetooth service. 3618- You can call the following APIs only after receiving an asynchronous callback: [readCharacteristicValue](#readcharacteristicvalue), [readDescriptorValue](#readdescriptorvalue), [writeCharacteristicValue](#writecharacteristicvalue), [writeDescriptorValue](#writedescriptorvalue), [getRssiValue](#getrssivalue), [setCharacteristicChangeNotification](#setcharacteristicchangenotification), and [setCharacteristicChangeIndication](#setcharacteristicchangeindication). 3619 3620**Required permissions**: ohos.permission.ACCESS_BLUETOOTH 3621 3622**Atomic service API**: This API can be used in atomic services since API version 12. 3623 3624**System capability**: SystemCapability.Communication.Bluetooth.Core 3625 3626**Parameters** 3627 3628| Name | Type | Mandatory | Description | 3629| -------------- | --------------------------------------- | ---- | ----------------------------- | 3630| characteristic | [BLECharacteristic](#blecharacteristic) | Yes | Characteristic of the server. | 3631| enable | boolean | Yes | Whether to enable characteristic change indication.<br>**true** to enable, **false** otherwise.| 3632 3633**Return value** 3634 3635| Type | Description | 3636| ---------------------------------------- | -------------------------- | 3637| Promise<void> | Promise used to return the result. that returns no value.| 3638 3639**Error codes** 3640 3641For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Bluetooth Error Codes](errorcode-bluetoothManager.md). 3642 3643| ID| Error Message| 3644| -------- | ---------------------------- | 3645|201 | Permission denied. | 3646|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 3647|801 | Capability not supported. | 3648|2900001 | Service stopped. | 3649|2900011 | The operation is busy. The last operation is not complete. | 3650|2900099 | Operation failed. | 3651|2901003 | The connection is not established. | 3652 3653**Example** 3654 3655```js 3656import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 3657// Create descriptors. 3658let descriptors: Array<ble.BLEDescriptor> = []; 3659let arrayBuffer = new ArrayBuffer(2); 3660let descV = new Uint8Array(arrayBuffer); 3661descV[0] = 0; // Use the Client Characteristic Configuration descriptor as an example. When bit 0 and bit 1 are both set to 0, the notification and indication functions are disabled. 3662let descriptor: ble.BLEDescriptor = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', 3663 characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', 3664 descriptorUuid: '00002902-0000-1000-8000-00805F9B34FB', descriptorValue: arrayBuffer}; 3665descriptors[0] = descriptor; 3666let arrayBufferC = new ArrayBuffer(8); 3667let characteristic: ble.BLECharacteristic = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', 3668 characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', characteristicValue: arrayBufferC, descriptors:descriptors}; 3669try { 3670 let device: ble.GattClientDevice = ble.createGattClientDevice('XX:XX:XX:XX:XX:XX'); 3671 device.setCharacteristicChangeIndication(characteristic, false); 3672} catch (err) { 3673 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 3674} 3675 3676``` 3677 3678 3679### on('BLECharacteristicChange') 3680 3681on(type: 'BLECharacteristicChange', callback: Callback<BLECharacteristic>): void 3682 3683Subscribes to the characteristic change events of the server. This API uses an asynchronous callback to return the result.<br> 3684- You can receive characteristic change notifications or indications only after calling [setCharacteristicChangeNotification](#setcharacteristicchangenotification) or [setCharacteristicChangeIndication](#setcharacteristicchangeindication) to enable the notification or indication function. 3685 3686**Required permissions**: ohos.permission.ACCESS_BLUETOOTH 3687 3688**Atomic service API**: This API can be used in atomic services since API version 12. 3689 3690**System capability**: SystemCapability.Communication.Bluetooth.Core 3691 3692**Parameters** 3693 3694| Name | Type | Mandatory | Description | 3695| -------- | ---------------------------------------- | ---- | ---------------------------------------- | 3696| type | string | Yes | Event type. The value **BLECharacteristicChange** indicates a characteristic change event.<br>This event is triggered when the client receives a characteristic change notification or indication from the server.| 3697| callback | Callback<[BLECharacteristic](#blecharacteristic)> | Yes | Callback used to return the updated characteristic. | 3698 3699**Error codes** 3700 3701For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 3702 3703| ID| Error Message| 3704| -------- | ---------------------------- | 3705|201 | Permission denied. | 3706|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 3707|801 | Capability not supported. | 3708 3709**Example** 3710 3711```js 3712import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 3713function CharacteristicChange(characteristicChangeReq: ble.BLECharacteristic) { 3714 let serviceUuid: string = characteristicChangeReq.serviceUuid; 3715 let characteristicUuid: string = characteristicChangeReq.characteristicUuid; 3716 let value: Uint8Array = new Uint8Array(characteristicChangeReq.characteristicValue); 3717} 3718try { 3719 let device: ble.GattClientDevice = ble.createGattClientDevice('XX:XX:XX:XX:XX:XX'); 3720 device.on('BLECharacteristicChange', CharacteristicChange); 3721} catch (err) { 3722 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 3723} 3724``` 3725 3726 3727### off('BLECharacteristicChange') 3728 3729off(type: 'BLECharacteristicChange', callback?: Callback<BLECharacteristic>): void 3730 3731Unsubscribes from the characteristic change events of the server. 3732 3733**Required permissions**: ohos.permission.ACCESS_BLUETOOTH 3734 3735**Atomic service API**: This API can be used in atomic services since API version 12. 3736 3737**System capability**: SystemCapability.Communication.Bluetooth.Core 3738 3739**Parameters** 3740 3741| Name | Type | Mandatory | Description | 3742| -------- | ---------------------------------------- | ---- | ---------------------------------------- | 3743| type | string | Yes | Event type. The value **BLECharacteristicChange** indicates a characteristic change event.| 3744| callback | Callback<[BLECharacteristic](#blecharacteristic)> | No | Callback to unregister.<br>If this parameter is specified, it must be the same as the callback in [on('BLECharacteristicChange')](#onblecharacteristicchange). If this parameter is not specified, all callbacks corresponding to the event type are unsubscribed.| 3745 3746**Error codes** 3747 3748For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 3749 3750| ID| Error Message| 3751| -------- | ---------------------------- | 3752|201 | Permission denied. | 3753|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 3754|801 | Capability not supported. | 3755 3756**Example** 3757 3758```js 3759import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 3760try { 3761 let device: ble.GattClientDevice = ble.createGattClientDevice('XX:XX:XX:XX:XX:XX'); 3762 device.off('BLECharacteristicChange'); 3763} catch (err) { 3764 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 3765} 3766``` 3767 3768 3769### on('BLEConnectionStateChange') 3770 3771on(type: 'BLEConnectionStateChange', callback: Callback<BLEConnectionChangeState>): void 3772 3773Subscribes to connection state change events of GATT profile on the client. This API uses an asynchronous callback to return the result. 3774 3775**Required permissions**: ohos.permission.ACCESS_BLUETOOTH 3776 3777**Atomic service API**: This API can be used in atomic services since API version 12. 3778 3779**System capability**: SystemCapability.Communication.Bluetooth.Core 3780 3781**Parameters** 3782 3783| Name | Type | Mandatory | Description | 3784| -------- | ---------------------------------------- | ---- | ---------------------------------------- | 3785| type | string | Yes | Event type. The value **BLEConnectionStateChange** indicates a connection state change event.<br>This event is triggered when the GATT connection state changes.<br>For example, the connection status may change when the client calls [connect](#connect) or [disconnect](#disconnect).| 3786| callback | Callback<[BLEConnectionChangeState](#bleconnectionchangestate)> | Yes | Callback used to return the GATT connection state change event. | 3787 3788**Error codes** 3789 3790For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 3791 3792| ID| Error Message| 3793| -------- | ---------------------------- | 3794|201 | Permission denied. | 3795|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 3796|801 | Capability not supported. | 3797 3798**Example** 3799 3800```js 3801import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 3802function ConnectStateChanged(state: ble.BLEConnectionChangeState) { 3803 console.info('bluetooth connect state changed'); 3804 let connectState: ble.ProfileConnectionState = state.state; 3805} 3806try { 3807 let device: ble.GattClientDevice = ble.createGattClientDevice('XX:XX:XX:XX:XX:XX'); 3808 device.on('BLEConnectionStateChange', ConnectStateChanged); 3809} catch (err) { 3810 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 3811} 3812``` 3813 3814 3815### off('BLEConnectionStateChange') 3816 3817off(type: 'BLEConnectionStateChange', callback?: Callback<BLEConnectionChangeState>): void 3818 3819Unsubscribes from connection state change events of GATT profile on the client. 3820 3821**Required permissions**: ohos.permission.ACCESS_BLUETOOTH 3822 3823**Atomic service API**: This API can be used in atomic services since API version 12. 3824 3825**System capability**: SystemCapability.Communication.Bluetooth.Core 3826 3827**Parameters** 3828 3829| Name | Type | Mandatory | Description | 3830| -------- | ---------------------------------------- | ---- | ---------------------------------------- | 3831| type | string | Yes | Event type. The value **BLEConnectionStateChange** indicates a connection state change event.| 3832| callback | Callback<[BLEConnectionChangeState](#bleconnectionchangestate)> | No | Callback to unregister.<br>If this parameter is specified, it must be the same as the callback in [on('BLEConnectionStateChange')](#onbleconnectionstatechange). If this parameter is not specified, all callbacks corresponding to the event type are unsubscribed.| 3833 3834**Error codes** 3835 3836For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 3837 3838| ID| Error Message| 3839| -------- | ---------------------------- | 3840|201 | Permission denied. | 3841|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 3842|801 | Capability not supported. | 3843 3844**Example** 3845 3846```js 3847import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 3848try { 3849 let device: ble.GattClientDevice = ble.createGattClientDevice('XX:XX:XX:XX:XX:XX'); 3850 device.off('BLEConnectionStateChange'); 3851} catch (err) { 3852 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 3853} 3854``` 3855 3856 3857### on('BLEMtuChange') 3858 3859on(type: 'BLEMtuChange', callback: Callback<number>): void 3860 3861Subscribes to MTU change events on the client. This API uses an asynchronous callback to return the result. 3862 3863**Required permissions**: ohos.permission.ACCESS_BLUETOOTH 3864 3865**Atomic service API**: This API can be used in atomic services since API version 12. 3866 3867**System capability**: SystemCapability.Communication.Bluetooth.Core 3868 3869**Parameters** 3870 3871| Name | Type | Mandatory | Description | 3872| -------- | ---------------------------------------- | ---- | ---------------------------------------- | 3873| type | string | Yes | Event type. The value **BLEMtuChange** indicates an MTU change event.<br>This event is triggered when the client initiates MTU negotiation by calling [setBLEMtuSize](#setblemtusize).| 3874| callback | Callback<number> | Yes | Callback used to return the negotiated MTU, in bytes.| 3875 3876**Error codes** 3877 3878For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 3879 3880| ID| Error Message| 3881| -------- | ---------------------------- | 3882|201 | Permission denied. | 3883|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 3884|801 | Capability not supported. | 3885 3886**Example** 3887 3888```js 3889import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 3890try { 3891 let gattClient: ble.GattClientDevice = ble.createGattClientDevice('XX:XX:XX:XX:XX:XX'); 3892 gattClient.on('BLEMtuChange', (mtu: number) => { 3893 console.info('BLEMtuChange, mtu: ' + mtu); 3894 }); 3895} catch (err) { 3896 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 3897} 3898``` 3899 3900 3901### off('BLEMtuChange') 3902 3903off(type: 'BLEMtuChange', callback?: Callback<number>): void 3904 3905Unsubscribes from MTU change events on the client. 3906 3907**Required permissions**: ohos.permission.ACCESS_BLUETOOTH 3908 3909**Atomic service API**: This API can be used in atomic services since API version 12. 3910 3911**System capability**: SystemCapability.Communication.Bluetooth.Core 3912 3913**Parameters** 3914 3915| Name | Type | Mandatory | Description | 3916| -------- | ---------------------------------------- | ---- | ---------------------------------------- | 3917| type | string | Yes | Event type. The value **BLEMtuChange** indicates an MTU change event.| 3918| callback | Callback<number> | No | Callback to unregister. If this parameter is specified, it must be the same as the callback in [on('BLEMtuChange')](#onblemtuchange-1). If this parameter is not specified, all callbacks corresponding to the event type are unsubscribed.| 3919 3920**Error codes** 3921 3922For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 3923 3924| ID| Error Message| 3925| -------- | ---------------------------- | 3926|201 | Permission denied. | 3927|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 3928|801 | Capability not supported. | 3929 3930**Example** 3931 3932```js 3933import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 3934try { 3935 let device: ble.GattClientDevice = ble.createGattClientDevice('XX:XX:XX:XX:XX:XX'); 3936 device.off('BLEMtuChange'); 3937} catch (err) { 3938 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 3939} 3940``` 3941 3942## ble.createBleScanner<sup>15+</sup> 3943 3944createBleScanner(): BleScanner 3945 3946Creates a [BleScanner](#blescanner15) instance, which can be used to initiate or stop the BLE scan. 3947 3948**Atomic service API**: This API can be used in atomic services since API version 15. 3949 3950**System capability**: SystemCapability.Communication.Bluetooth.Core 3951 3952**Return value** 3953 3954| Type| Description| 3955| ------------ | ------------- | 3956| [BleScanner](#blescanner15) | **BleScanner** instance.| 3957 3958**Example** 3959 3960```js 3961import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 3962import { ble } from '@kit.ConnectivityKit'; 3963let bleScanner: ble.BleScanner = ble.createBleScanner(); 3964console.info('create bleScanner success'); 3965``` 3966 3967## BleScanner<sup>15+</sup> 3968 3969Represents the BLE scanner class, which provides scan-related APIs.<br> 3970- Before using the APIs of this class, you need to call [createBleScanner](#blecreateblescanner15) to construct a BLE scanner instance.<br> 3971- You can create multiple instances of this class to manage multiple scan processes. 3972 3973### startScan<sup>15+</sup> 3974 3975startScan(filters: Array<ScanFilter>, options?: ScanOptions): Promise<void> 3976 3977Starts BLE scanning. This API uses a promise to return the result.<br> 3978- This API can be used to scan only BLE devices.<br> 3979- You can obtain the scan result through the callback of [on('BLEDeviceFind')](#onbledevicefind15).<br> 3980- You can call [stopScan](#stopscan15) to stop the BLE scan. 3981 3982**Required permissions**: ohos.permission.ACCESS_BLUETOOTH 3983 3984**Atomic service API**: This API can be used in atomic services since API version 15. 3985 3986**System capability**: SystemCapability.Communication.Bluetooth.Core 3987 3988**Parameters** 3989 3990| Name | Type | Mandatory | Description | 3991| ------- | -------------------------------------- | ---- | ----------------------------------- | 3992| filters | Array<[ScanFilter](#scanfilter)> | Yes | Filter criteria for BLE advertising. Devices that meet the filter criteria will be reported.<br>If this parameter is set to **null**, all discoverable BLE devices nearby will be scanned. However, this method is not recommended as it may pick up unexpected devices and increase power consumption.| 3993| options | [ScanOptions](#scanoptions) | No | Defines the scan configuration parameters. | 3994 3995**Return value** 3996 3997| Type | Description | 3998| ---------------------------------------- | -------------------------- | 3999| Promise<void> | Promise used to return the result. that returns no value.| 4000 4001**Error codes** 4002 4003For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Bluetooth Error Codes](errorcode-bluetoothManager.md). 4004 4005| ID| Error Message| 4006| -------- | ---------------------------- | 4007|201 | Permission denied. | 4008|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 4009|801 | Capability not supported. | 4010|2900001 | Service stopped. | 4011|2900003 | Bluetooth disabled. | 4012|2900009 | Fails to start scan as it is out of hardware resources. | 4013|2900099 | Operation failed. | 4014|2902050 | Failed to start scan as Ble scan is already started by the app.| 4015 4016**Example** 4017 4018```js 4019import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 4020import { ble } from '@kit.ConnectivityKit'; 4021let bleScanner: ble.BleScanner = ble.createBleScanner(); 4022function onReceiveEvent(scanReport: ble.ScanReport) { 4023 console.info('BLE scan device find result = '+ JSON.stringify(scanReport)); 4024} 4025try { 4026 bleScanner.on("BLEDeviceFind", onReceiveEvent); 4027 let scanFilter: ble.ScanFilter = { 4028 deviceId:"XX:XX:XX:XX:XX:XX", 4029 name:"test", 4030 serviceUuid:"00001888-0000-1000-8000-00805f9b34fb" 4031 }; 4032 let scanOptions: ble.ScanOptions = { 4033 interval: 500, 4034 dutyMode: ble.ScanDuty.SCAN_MODE_LOW_POWER, 4035 matchMode: ble.MatchMode.MATCH_MODE_AGGRESSIVE, 4036 reportMode: ble.ScanReportMode.FENCE_SENSITIVITY_LOW 4037 } 4038 bleScanner.startScan([scanFilter],scanOptions); 4039 console.info('startScan success'); 4040} catch (err) { 4041 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 4042} 4043``` 4044 4045### stopScan<sup>15+</sup> 4046 4047stopScan(): Promise<void> 4048 4049Stops an ongoing BLE scan.<br> 4050- This API works for a scan initiated by calling [startScan](#startscan15).<br> 4051- Call this API to stop the Bluetooth scan if device discovery is no longer needed. 4052 4053**Required permissions**: ohos.permission.ACCESS_BLUETOOTH 4054 4055**Atomic service API**: This API can be used in atomic services since API version 15. 4056 4057**System capability**: SystemCapability.Communication.Bluetooth.Core 4058 4059**Return value** 4060 4061| Type | Description | 4062| ---------------------------------------- | -------------------------- | 4063| Promise<void> | Promise used to return the result. that returns no value.| 4064 4065**Error codes** 4066 4067For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Bluetooth Error Codes](errorcode-bluetoothManager.md). 4068 4069| ID| Error Message| 4070| -------- | ---------------------------- | 4071|201 | Permission denied. | 4072|801 | Capability not supported. | 4073|2900001 | Service stopped. | 4074|2900003 | Bluetooth disabled. | 4075|2900099 | Operation failed. | 4076 4077**Example** 4078 4079```js 4080import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 4081import { ble } from '@kit.ConnectivityKit'; 4082let bleScanner: ble.BleScanner = ble.createBleScanner(); 4083try { 4084 bleScanner.stopScan(); 4085 console.info('stopScan success'); 4086} catch (err) { 4087 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 4088} 4089``` 4090 4091### on('BLEDeviceFind')<sup>15+</sup> 4092 4093on(type: 'BLEDeviceFind', callback: Callback<ScanReport>): void 4094 4095Subscribes to BLE scan result reporting events. This API uses an asynchronous callback to return the result. 4096 4097**Required permissions**: ohos.permission.ACCESS_BLUETOOTH 4098 4099**Atomic service API**: This API can be used in atomic services since API version 15. 4100 4101**System capability**: SystemCapability.Communication.Bluetooth.Core 4102 4103**Parameters** 4104 4105| Name | Type | Mandatory | Description | 4106| -------- | ---------------------------------------- | ---- | ----------------------------------- | 4107| type | string | Yes | Event type. The value **BLEDeviceFind** indicates a scan result reporting event.<br>This event is triggered if a BLE device is discovered when [startScan](#startscan15) is called. | 4108| callback | Callback<[ScanReport](#scanreport15)> | Yes | Callback used to return the set of scan results.| 4109 4110**Error codes** 4111 4112For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Bluetooth Error Codes](errorcode-bluetoothManager.md). 4113 4114| ID| Error Message| 4115| -------- | ---------------------------- | 4116|201 | Permission denied. | 4117|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 4118|801 | Capability not supported. | 4119|2900099 | Operation failed. | 4120 4121**Example** 4122 4123```js 4124import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 4125import { ble } from '@kit.ConnectivityKit'; 4126function onReceiveEvent(scanReport: ble.ScanReport) { 4127 console.info('bluetooth device find = '+ JSON.stringify(scanReport)); 4128} 4129let bleScanner: ble.BleScanner = ble.createBleScanner(); 4130try { 4131 bleScanner.on('BLEDeviceFind', onReceiveEvent); 4132} catch (err) { 4133 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 4134} 4135``` 4136 4137### off('BLEDeviceFind')<sup>15+</sup> 4138 4139off(type: 'BLEDeviceFind', callback?: Callback<ScanReport>): void 4140 4141Unsubscribes from BLE scan result reporting events.<br> 4142- After [stopScan](#stopscan15) is called to stop the BLE scan, call this API to unsubscribe from scan result reporting events if device discovery is no longer needed. 4143 4144**Required permissions**: ohos.permission.ACCESS_BLUETOOTH 4145 4146**Atomic service API**: This API can be used in atomic services since API version 15. 4147 4148**System capability**: SystemCapability.Communication.Bluetooth.Core 4149 4150**Parameters** 4151 4152| Name | Type | Mandatory | Description | 4153| -------- | ---------------------------------------- | ---- | ---------------------------------------- | 4154| type | string | Yes | Event type. The value **BLEDeviceFind** indicates a scan result reporting event. | 4155| callback | Callback<[ScanReport](#scanreport15)> | No | Callback to unregister.<br>If this parameter is specified, it must be the same as the callback in [on('BLEDeviceFind')](#onbledevicefind15). If this parameter is not specified, all callbacks corresponding to the event type are unsubscribed.| 4156 4157**Error codes** 4158 4159For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Bluetooth Error Codes](errorcode-bluetoothManager.md). 4160 4161| ID| Error Message| 4162| -------- | ---------------------------- | 4163|201 | Permission denied. | 4164|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 4165|801 | Capability not supported. | 4166|2900099 | Operation failed. | 4167 4168**Example** 4169 4170```js 4171import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 4172import { ble } from '@kit.ConnectivityKit'; 4173function onReceiveEvent(scanReport: ble.ScanReport) { 4174 console.info('bluetooth device find = '+ JSON.stringify(scanReport)); 4175} 4176let bleScanner: ble.BleScanner = ble.createBleScanner(); 4177try { 4178 bleScanner.on('BLEDeviceFind', onReceiveEvent); 4179 bleScanner.off('BLEDeviceFind', onReceiveEvent); 4180} catch (err) { 4181 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 4182} 4183``` 4184 4185## GattService 4186 4187Defines the structure of GATT service, which can contain multiple [characteristics](#blecharacteristic) and other dependent services. 4188 4189**Atomic service API**: This API can be used in atomic services since API version 12. 4190 4191**System capability**: SystemCapability.Communication.Bluetooth.Core 4192 4193| Name | Type | Read-Only| Optional | Description | 4194| --------------- | ---------------------------------------- |---- | ---- | ---------------------------------------- | 4195| serviceUuid | string | No| No | UUID of the GATT service. for example, 00001888-0000-1000-8000-00805f9b34fb.| 4196| isPrimary | boolean | No| No | Whether the service is a primary service. The value **true** indicates that the service is a primary service, and the value **false** indicates the opposite. | 4197| characteristics | Array<[BLECharacteristic](#blecharacteristic)> | No| No | Characteristics of the GATT service. | 4198| includeServices | Array<[GattService](#gattservice)> | No| Yes | Services on which the service depends. | 4199 4200 4201 4202## BLECharacteristic 4203 4204Defines the structure of GATT characteristic, which is the core data unit of [GattService](#gattservice). 4205 4206**System capability**: SystemCapability.Communication.Bluetooth.Core 4207 4208| Name | Type | Read-Only| Optional | Description | 4209| ------------------- | ---------------------------------------- | ---- | ---- | ---------------------------------------- | 4210| serviceUuid | string | No| No | Service UUID of the characteristic. for example, 00001888-0000-1000-8000-00805f9b34fb.<br>**Atomic service API**: This API can be used in atomic services since API version 12.| 4211| characteristicUuid | string | No| No | Characteristic UUID. for example, 00002a11-0000-1000-8000-00805f9b34fb.<br>**Atomic service API**: This API can be used in atomic services since API version 12.| 4212| characteristicValue | ArrayBuffer | No| No | Characteristic value.<br>**Atomic service API**: This API can be used in atomic services since API version 12. | 4213| descriptors | Array<[BLEDescriptor](#bledescriptor)> | No| No | Descriptors contained in the characteristic.<br>**Atomic service API**: This API can be used in atomic services since API version 12. | 4214| properties | [GattProperties](#gattproperties) | No| Yes | Properties supported by the characteristic.<br>**Atomic service API**: This API can be used in atomic services since API version 12. | 4215| characteristicValueHandle<sup>18+</sup> | number | No | Yes | Unique handle of the characteristic. It can be used to distinguish descriptors if the BLE device that serves as the server provides multiple descriptors with the same UUID.<br>**Atomic service API**: This API can be used in atomic services since API version 18. | 4216| permissions<sup>20+</sup> | [GattPermissions](#gattpermissions20) | No | Yes | Permissions required for characteristic read and write operations.<br>**Atomic service API**: This API can be used in atomic services since API version 20. | 4217 4218 4219## BLEDescriptor 4220 4221Defines the structure of GATT descriptor, which is the data unit of [BLECharacteristic](#blecharacteristic) and is used to describe the additional information and properties of the characteristic. 4222 4223**System capability**: SystemCapability.Communication.Bluetooth.Core 4224 4225| Name | Type | Read-Only| Optional | Description | 4226| ------------------ | ----------- | ---- | ---- | ---------------------------------------- | 4227| serviceUuid | string | No| No | Service UUID of the characteristic. for example, 00001888-0000-1000-8000-00805f9b34fb.<br>**Atomic service API**: This API can be used in atomic services since API version 12.| 4228| characteristicUuid | string | No| No | Characteristic UUID of the descriptor. for example, 00002a11-0000-1000-8000-00805f9b34fb.<br>**Atomic service API**: This API can be used in atomic services since API version 12.| 4229| descriptorUuid | string | No| No | Descriptor UUID. for example, 00002902-0000-1000-8000-00805f9b34fb.<br>**Atomic service API**: This API can be used in atomic services since API version 12.| 4230| descriptorValue | ArrayBuffer | No| No | Descriptor value.<br>**Atomic service API**: This API can be used in atomic services since API version 12. | 4231| descriptorHandle<sup>18+</sup> | number | No | Yes | Unique handle of the descriptor. It can be used to distinguish descriptors if the BLE device that serves as the server provides multiple descriptors with the same UUID.<br>**Atomic service API**: This API can be used in atomic services since API version 18. | 4232| permissions<sup>20+</sup> | [GattPermissions](#gattpermissions20) | No | Yes | Permissions required for descriptor read and write operations.<br>**Atomic service API**: This API can be used in atomic services since API version 20. | 4233 4234 4235## NotifyCharacteristic 4236 4237Defines the structure of characteristic notification. 4238 4239**Atomic service API**: This API can be used in atomic services since API version 12. 4240 4241**System capability**: SystemCapability.Communication.Bluetooth.Core 4242 4243| Name | Type | Read-Only| Optional | Description | 4244| ------------------- | ----------- | ---- | ---- | ---------------------------------------- | 4245| serviceUuid | string | No| No | Service UUID of the characteristic. for example, 00001888-0000-1000-8000-00805f9b34fb.| 4246| characteristicUuid | string | No| No | Characteristic UUID. for example, 00002a11-0000-1000-8000-00805f9b34fb.| 4247| characteristicValue | ArrayBuffer | No| No | Characteristic value. | 4248| confirm | boolean | No| No | Whether confirmation is required. The value **true** indicates that confirmation is required for an indication, and the value **false** indicates that confirmation is not required for a notification.| 4249 4250 4251## CharacteristicReadRequest 4252 4253Defines the structure of characteristic read request sent from the client. 4254 4255**Atomic service API**: This API can be used in atomic services since API version 12. 4256 4257**System capability**: SystemCapability.Communication.Bluetooth.Core 4258 4259| Name | Type | Read-Only| Optional | Description | 4260| ------------------ | ------ | ---- | ---- | ---------------------------------------- | 4261| deviceId | string | No| No | Bluetooth device address of the client. for example, XX:XX:XX:XX:XX:XX.| 4262| transId | number | No| No | Transaction identifier of the characteristic read request. It must be the same as the **transId** in the response returned by the server. | 4263| offset | number | No| No | Read offset of the client. For example, **k** indicates that the read starts from the kth byte.<br>It must be the same as the **offset** in the response returned by the server.| 4264| characteristicUuid | string | No| No | Characteristic UUID. for example, 00002a11-0000-1000-8000-00805f9b34fb.| 4265| serviceUuid | string | No| No | Service UUID of the characteristic. for example, 00001888-0000-1000-8000-00805f9b34fb.| 4266 4267 4268## CharacteristicWriteRequest 4269 4270Defines the structure of characteristic write request sent from the client. 4271 4272**Atomic service API**: This API can be used in atomic services since API version 12. 4273 4274**System capability**: SystemCapability.Communication.Bluetooth.Core 4275 4276| Name | Type | Read-Only| Optional | Description | 4277| ------------------ | ------ | ---- | ---- | ---------------------------------------- | 4278| deviceId | string | No| No | Bluetooth device address of the client. for example, XX:XX:XX:XX:XX:XX.| 4279| transId | number | No| No | Transaction identifier of the characteristic write request. It must be the same as the **transId** in the response returned by the server. | 4280| offset | number | No| No | Write offset of the client. For example, **k** indicates that the write starts from the kth byte.<br>It must be the same as the **offset** in the response returned by the server.| 4281| isPrepared | boolean | No| No | Whether to respond immediately after receiving a write request from the client.<br>The value **true** means to respond at a later time, and the value **false** means to respond immediately.| 4282| needRsp | boolean | No| No | Whether to respond to the client.<br>The value **true** means to respond to the client, and the value **false** means to respond immediately.| 4283| value | ArrayBuffer | No| No | Characteristic value to write.| 4284| characteristicUuid | string | No| No | Characteristic UUID. for example, 00002a11-0000-1000-8000-00805f9b34fb.| 4285| serviceUuid | string | No| No | Service UUID of the characteristic. for example, 00001888-0000-1000-8000-00805f9b34fb.| 4286 4287 4288## DescriptorReadRequest 4289 4290Defines the structure of descriptor read request sent from the client. 4291 4292**Atomic service API**: This API can be used in atomic services since API version 12. 4293 4294**System capability**: SystemCapability.Communication.Bluetooth.Core 4295 4296| Name | Type | Read-Only| Optional | Description | 4297| ------------------ | ------ | ---- | ---- | ---------------------------------------- | 4298| deviceId | string | No| No | Bluetooth device address of the client. for example, XX:XX:XX:XX:XX:XX.| 4299| transId | number | No| No | Transaction identifier of the characteristic read request. It must be the same as the **transId** in the response returned by the server. | 4300| offset | number | No| No | Read offset of the client. For example, **k** indicates that the read starts from the kth byte.<br>It must be the same as the **offset** in the response returned by the server.| 4301| descriptorUuid | string | No| No | Descriptor UUID. for example, 00002902-0000-1000-8000-00805f9b34fb.| 4302| characteristicUuid | string | No| No | Characteristic UUID of the descriptor. for example, 00002a11-0000-1000-8000-00805f9b34fb.| 4303| serviceUuid | string | No| No | Service UUID of the characteristic. for example, 00001888-0000-1000-8000-00805f9b34fb.| 4304 4305 4306## DescriptorWriteRequest 4307 4308Defines the structure of descriptor write request sent from the client. 4309 4310**Atomic service API**: This API can be used in atomic services since API version 12. 4311 4312**System capability**: SystemCapability.Communication.Bluetooth.Core 4313 4314| Name | Type | Read-Only| Optional | Description | 4315| ------------------ | ----------- | ---- | ---- | ---------------------------------------- | 4316| deviceId | string | No| No | Bluetooth device address of the client. for example, XX:XX:XX:XX:XX:XX.| 4317| transId | number | No| No | Transaction identifier of the characteristic write request. It must be the same as the **transId** in the response returned by the server. | 4318| offset | number | No| No | Write offset of the client. For example, **k** indicates that the write starts from the kth byte.<br>It must be the same as the **offset** in the response returned by the server.| 4319| isPrepared | boolean | No| No | Whether to respond immediately after receiving a write request from the client.<br>The value **true** means to respond at a later time, and the value **false** means to respond immediately. | 4320| needRsp | boolean | No| No | Whether to respond to the client.<br>The value **true** means to respond to the client, and the value **false** means to respond immediately. | 4321| value | ArrayBuffer | No| No | Descriptor value to write. | 4322| descriptorUuid | string | No| No | Descriptor UUID. for example, 00002902-0000-1000-8000-00805f9b34fb.| 4323| characteristicUuid | string | No| No | Characteristic UUID of the descriptor. for example, 00002a11-0000-1000-8000-00805f9b34fb.| 4324| serviceUuid | string | No| No | Service UUID of the characteristic. for example, 00001888-0000-1000-8000-00805f9b34fb.| 4325 4326 4327## ServerResponse 4328 4329Defines the structure of server response to a read/write request from the client. 4330 4331**Atomic service API**: This API can be used in atomic services since API version 12. 4332 4333**System capability**: SystemCapability.Communication.Bluetooth.Core 4334 4335| Name | Type | Read-Only| Optional | Description | 4336| -------- | ----------- | ---- | ---- | -------------------------------------- | 4337| deviceId | string | No| No | Bluetooth device address of the client. for example, XX:XX:XX:XX:XX:XX. | 4338| transId | number | No| No | Transaction identifier of the read/write request. It must be the same as the **transId** in the response returned by the server. | 4339| status | number | No| No | Response state. Set this parameter to **0**, which indicates a normal response. | 4340| offset | number | No| No | Read/write offset. It must be the same as the **offset** in the read/write request sent from the client.| 4341| value | ArrayBuffer | No| No | Response data. | 4342 4343 4344## BLEConnectionChangeState 4345 4346Defines the connection status of the GATT profile. 4347 4348**Atomic service API**: This API can be used in atomic services since API version 12. 4349 4350**System capability**: SystemCapability.Communication.Bluetooth.Core 4351 4352| Name | Type | Read-Only| Optional| Description | 4353| -------- | ------------------------------------------------- | ---- | ---- | --------------------------------------------- | 4354| deviceId | string | No| No | Peer Bluetooth device address. for example, XX:XX:XX:XX:XX:XX.| 4355| state | [ProfileConnectionState](js-apis-bluetooth-constant.md#profileconnectionstate) | No| No | Connection status of the GATT profile. | 4356 4357 4358## ScanResult 4359 4360Defines the scan result to be reported upon scanning advertising packets that meet the filter criteria. 4361 4362**Atomic service API**: This API can be used in atomic services since API version 12. 4363 4364**System capability**: SystemCapability.Communication.Bluetooth.Core 4365 4366| Name | Type | Read-Only| Optional | Description | 4367| -------- | ----------- | ---- | ---- | ---------------------------------- | 4368| deviceId | string | No| No | Bluetooth device address. for example, XX:XX:XX:XX:XX:XX.<br>For security purposes, the device addresses obtained are virtual MAC addresses.<br>- The virtual address remains unchanged after a device is paired successfully.<br>- If a device is unpaired or Bluetooth is disabled, the virtual address will change after the device is paired again.<br>- To persistently save the addresses, call [access.addPersistentDeviceId](js-apis-bluetooth-access.md#accessaddpersistentdeviceid16).| 4369| rssi | number | No| No | Signal strength, in dBm. | 4370| data | ArrayBuffer | No| No | Advertising data sent by the discovered device. | 4371| deviceName | string | No| No | Device name. | 4372| connectable | boolean | No| No | Whether the discovered device is connectable. The value **true** indicates that the discovered device is connectable, and the value **false** indicates the opposite. | 4373 4374 4375## AdvertiseSetting 4376 4377Defines the BLE advertising parameters. 4378 4379**Atomic service API**: This API can be used in atomic services since API version 12. 4380 4381**System capability**: SystemCapability.Communication.Bluetooth.Core 4382 4383| Name | Type | Read-Only| Optional | Description | 4384| ----------- | ------- | ---- | ---- | ---------------------------------------- | 4385| interval | number | No| Yes | Advertising interval.<br>The value range is [32, 16777215], in slots. One slot represents 0.625 ms. The default value is **1600**.<br>The maximum value is **16384** for traditional advertising.| 4386| txPower | number | No| Yes | Transmit power. The value range is [–127, 1], in dBm. The default value is **–7**.<br>Considering performance and power consumption, the recommended parameter values are as follows: **1** for high level, **-7** for medium level, and **-15** for low level. | 4387| connectable | boolean | No| Yes | Whether the advertising is connectable. The value **true** indicates that the advertising is connectable, and the value false indicates the opposite. The default value is **true**. | 4388 4389 4390## AdvertiseData 4391 4392Defines the BLE advertising packet data, which can also be used in the response to a scan request. Currently, only traditional advertising is supported. The maximum length of the packet data is 31 bytes. The advertising will fail if the maximum length is exceeded. When all parameters are included (especially the Bluetooth device name), ensure the length of advertising packet data does not exceed 31 bytes. 4393 4394**System capability**: SystemCapability.Communication.Bluetooth.Core 4395 4396| Name | Type | Read-Only| Optional | Description | 4397| --------------- | ---------------------------------------- | ---- | ---- | --------------------------- | 4398| serviceUuids | Array<string> | No| No | Service UUID.<br>**Atomic service API**: This API can be used in atomic services since API version 12.| 4399| manufactureData | Array<[ManufactureData](#manufacturedata)> | No| No | Manufacturer data.<br>**Atomic service API**: This API can be used in atomic services since API version 12. | 4400| serviceData | Array<[ServiceData](#servicedata)> | No| No | Service data.<br>**Atomic service API**: This API can be used in atomic services since API version 12. | 4401| includeDeviceName | boolean | No| Yes | Whether to include the Bluetooth device name. The value **true** means to include the Bluetooth device name, and the value **false** means the opposite. The default value is **false**.<br>**Atomic service API**: This API can be used in atomic services since API version 12. | 4402| includeTxPower<sup>18+</sup> | boolean | No | Yes | Whether to include the transmit power.<br>The value **true** means to include the transmit power, and the value **false** means the opposite. The default value is **false**.<br>This parameter occupies three bytes.<br>**Atomic service API**: This API can be used in atomic services since API version 18. | 4403 4404 4405## AdvertisingParams<sup>11+</sup> 4406 4407Defines the parameters for initial BLE advertising. 4408 4409**System capability**: SystemCapability.Communication.Bluetooth.Core 4410 4411| Name | Type | Read-Only| Optional | Description | 4412| ------------------- | ------------------------------- | ----- | ----- | ------------------------ | 4413| advertisingSettings<sup>11+</sup> | [AdvertiseSetting](#advertisesetting) | No| No | Advertising settings. | 4414| advertisingData<sup>11+</sup> | [AdvertiseData](#advertisedata) | No| No | Advertising data. | 4415| advertisingResponse<sup>11+</sup> | [AdvertiseData](#advertisedata) | No| Yes | Advertising response.| 4416| duration<sup>11+</sup> | number | No| Yes | Advertising duration. The value range is [1,65535], in 10 ms.<br>If this parameter is not specified or set to **0**, advertising packets are sent continuously. | 4417 4418## AdvertisingEnableParams<sup>11+</sup> 4419 4420Defines the parameters for enabling BLE advertising. 4421 4422**System capability**: SystemCapability.Communication.Bluetooth.Core 4423 4424| Name | Type | Read-Only| Optional | Description | 4425| ------------------- | --------------------- | ----- | ----- | ------------------------ | 4426| advertisingId | number | No| No | Advertising ID. | 4427| duration | number | No| Yes | Advertising duration. The value range is [1,65535], in 10 ms.<br>If this parameter is not specified or set to **0**, advertising packets are sent continuously. | 4428 4429## AdvertisingDisableParams<sup>11+</sup> 4430 4431Defines the parameters for disabling BLE advertising. 4432 4433**System capability**: SystemCapability.Communication.Bluetooth.Core 4434 4435| Name | Type | Read-Only| Optional | Description | 4436| ------------------- | --------------------- | ----- | ----- | ------------------------ | 4437| advertisingId | number | No| No | Advertising ID. | 4438 4439## AdvertisingStateChangeInfo<sup>11+</sup> 4440 4441Defines the BLE advertising status information. 4442 4443**System capability**: SystemCapability.Communication.Bluetooth.Core 4444 4445| Name | Type | Read-Only| Optional | Description | 4446| ------------------- | --------------------------------------- | ----- | ----- | ------------------------ | 4447| advertisingId | number | No| No |Advertising ID. It is assigned in initial advertising and is used to identify subsequent advertising operations. | 4448| state | [AdvertisingState](#advertisingstate11) | No| No | BLE advertising status. | 4449 4450## ManufactureData 4451 4452Defines the manufacturer data in the BLE advertising packet data. 4453 4454**Atomic service API**: This API can be used in atomic services since API version 12. 4455 4456**System capability**: SystemCapability.Communication.Bluetooth.Core 4457 4458| Name | Type | Read-Only| Optional | Description | 4459| ---------------- | ------------------- | ---- | ---- | ------------------ | 4460| manufactureId | number | No| No | Manufacturer ID allocated by the Bluetooth Special Interest Group (SIG).| 4461| manufactureValue | ArrayBuffer | No| No | Manufacturer data. | 4462 4463 4464## ServiceData 4465 4466Represents the service data in the BLE advertising packet data. 4467 4468**Atomic service API**: This API can be used in atomic services since API version 12. 4469 4470**System capability**: SystemCapability.Communication.Bluetooth.Core 4471 4472| Name | Type | Read-Only| Optional | Description | 4473| ------------ | ----------- | ---- | ---- | ---------- | 4474| serviceUuid | string | No | No | Service UUID.| 4475| serviceValue | ArrayBuffer | No | No | Service data. | 4476 4477 4478## ScanFilter 4479 4480Defines the scan filters for BLE advertising packet data. Only advertising packets that meet the filter criteria are reported. 4481 4482**Atomic service API**: This API can be used in atomic services since API version 12. 4483 4484**System capability**: SystemCapability.Communication.Bluetooth.Core 4485 4486| Name | Type | Read-Only| Optional | Description | 4487| ------------------------------------------ | -------- | ---- | ---- | ------------------------------------------------------------ | 4488| deviceId | string | No| Yes | BLE device address. for example, XX:XX:XX:XX:XX:XX. | 4489| name | string | No| Yes | BLE device name. | 4490| serviceUuid | string | No| Yes | Service UUID. for example, 00001888-0000-1000-8000-00805f9b34fb.| 4491| serviceUuidMask | string | No| Yes | Service UUID mask. This parameter can be used with **serviceUuid** to filter specific service UUIDs. for example, FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF.| 4492| serviceSolicitationUuid | string | No| Yes | Service solicitation UUID. for example, 00001888-0000-1000-8000-00805F9B34FB.| 4493| serviceSolicitationUuidMask | string | No| Yes | Service solicitation UUID mask. This parameter can be used with **serviceSolicitationUuid** to filter specific service solicitation UUIDs. for example, FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF.| 4494| serviceData | ArrayBuffer | No| Yes | Service data. for example, [0x90,0x00,0xF1,0xF2].| 4495| serviceDataMask | ArrayBuffer | No| Yes | Service data mask. This parameter can be used with **serviceData** to filter specific service data. for example, [0xFF,0xFF,0xFF,0xFF].| 4496| manufactureId | number | No| Yes | Manufacturer ID. for example, 0x0006. | 4497| manufactureData | ArrayBuffer | No| Yes | Manufacturer data. This parameter can be used with **manufactureId** to filter specific manufacturers. for example, [0x1F,0x2F,0x3F].| 4498| manufactureDataMask | ArrayBuffer | No| Yes | Manufacturer data mask. This parameter can be used with **manufactureData** to filter specific manufacturer data. for example, [0xFF,0xFF,0xFF].| 4499 4500 4501## ScanOptions 4502 4503Defines the scan options. 4504 4505**System capability**: SystemCapability.Communication.Bluetooth.Core 4506 4507| Name | Type | Read-Only| Optional | Description | 4508| --------- | ----------------------- | ---- | ---- | -------------------------------------- | 4509| interval | number | No| Yes | Delay for reporting the scan result, in ms. The default value is **0**. This parameter is used together with [ScanReportMode](#scanreportmode15).<br>- This parameter does not take effect in normal and geofence scan reporting modes. The advertising packets that meet the filtering criteria are reported immediately.<br>- This parameter takes effect in batch scan reporting mode. The advertising packets that meet the filtering criteria are stored in the cache queue and reported after the specified delay. If this parameter is not set or its value is in the range of [0, 5000), the Bluetooth subsystem sets the delay to **5000** by default. If the number of advertising packets that meet the filtering criteria exceeds the hardware's cache capability within the specified delay, the Bluetooth subsystem reports the scan result in advance.<br>**Atomic service API**: This API can be used in atomic services since API version 12. | 4510| dutyMode | [ScanDuty](#scanduty) | No| Yes | Scan mode. The default value is **SCAN_MODE_LOW_POWER**.<br>**Atomic service API**: This API can be used in atomic services since API version 12. | 4511| matchMode | [MatchMode](#matchmode) | No| Yes | Hardware match mode. The default value is **MATCH_MODE_AGGRESSIVE**.<br>**Atomic service API**: This API can be used in atomic services since API version 12.| 4512| phyType<sup>12+</sup> | [PhyType](#phytype12) | No| Yes | Physical channel type. The default value is **PHY_LE_1M**.<br>**Atomic service API**: This API can be used in atomic services since API version 12.| 4513| reportMode<sup>15+</sup> | [ScanReportMode](#scanreportmode15) | No| Yes | Reporting mode. The default value is **NORMAL**.<br>**Atomic service API**: This API can be used in atomic services since API version 15.| 4514 4515 4516## GattProperties 4517 4518Describes the properties supported by a GATT characteristic. The properties determine how the characteristic and its descriptors are used and accessed. 4519 4520**System capability**: SystemCapability.Communication.Bluetooth.Core 4521 4522| Name | Type | Read-Only| Optional | Description | 4523| -------- | ------ |---- |---- | ----------- | 4524| write | boolean | No| Yes | Whether the write operation is supported.<br>The value **true** indicates that the write operation is supported and a response is required, and the value **false** indicates that the write operation is not supported. The default value is **true**.<br>**Atomic service API**: This API can be used in atomic services since API version 12.| 4525| writeNoResponse | boolean | No| Yes | Whether the write operation is supported.<br>The value **true** indicates that the write operation is supported without requiring a response, and the value **false** indicates that the write operation is not supported. The default value is **true**.<br>**Atomic service API**: This API can be used in atomic services since API version 12.| 4526| read | boolean | No| Yes | Whether the read operation is supported.<br>**true** if it has flash, **false** otherwise. The default value is **true**.<br>**Atomic service API**: This API can be used in atomic services since API version 12.| 4527| notify | boolean | No| Yes | Whether the notification operation is supported.<br>The value **true** indicates that the notification operation is supported and a response is required, and the value **false** indicates the notification operation is not supported. false<br>**Atomic service API**: This API can be used in atomic services since API version 12.| 4528| indicate | boolean | No| Yes | Whether the indication operation is supported.<br>The value **true** indicates that the indication operation is supported without requiring a response, and the value **false** indicates the indication operation is not supported. false<br>**Atomic service API**: This API can be used in atomic services since API version 12.| 4529| broadcast<sup>20+</sup> | boolean | No| Yes | Whether the characteristic can be sent by the server in advertising packets.<br>The value **true** indicates that the characteristic can be sent by the server as [ServiceData](#servicedata) in advertising packets, and the value **false** indicates the opposite. false<br>**Atomic service API**: This API can be used in atomic services since API version 20.| 4530| authenticatedSignedWrite<sup>20+</sup> | boolean | No| Yes | Whether the characteristic can be written with a signature.<br>The value **true** indicates that the characteristic can be written with a signature, and the value **false** indicates the opposite. Set this parameter to **true** if you want to replace the encryption process with signature verification. Ensure that **writeSigned** or **writeSignedMitm** in [GattPermissions](#gattpermissions20) is also set to **true**. Otherwise, this parameter does not take effect. false<br>**Atomic service API**: This API can be used in atomic services since API version 20.| 4531| extendedProperties<sup>20+</sup> | boolean | No| Yes | Whether the characteristic has extended attributes.<br>The value **true** indicates that the characteristic has extended attributes, and the value **false** indicates the opposite. false<br>**Atomic service API**: This API can be used in atomic services since API version 20.| 4532 4533 4534## GattPermissions<sup>20+</sup> 4535 4536Defines the permissions required for GATT characteristic or descriptor read/write operations. 4537 4538**Atomic service API**: This API can be used in atomic services since API version 20. 4539 4540**System capability**: SystemCapability.Communication.Bluetooth.Core 4541 4542| Name | Type | Read-Only| Optional | Description | 4543| -------- | ------ |---- |---- | ----------- | 4544| read | boolean | No| Yes | Whether reading characteristics or descriptors is allowed.<br>**true** to enable, **false** otherwise. The default value is **true**.| 4545| readEncrypted | boolean | No| Yes | Whether the characteristic or descriptor needs to be encrypted before being read.<br>The value **true** indicates that the characteristic or descriptor needs to be encrypted before being read, and the value **false** indicates the opposite. The default value is **false**.| 4546| readEncryptedMitm | boolean | No| Yes | Whether the characteristic or descriptor to be read needs to be encrypted to prevent man-in-the-middle (MITM) attacks.<br>Enabling encryption helps to prevent data from being tampered with by a third party. The value **true** means to enable encryption, and the value **false** indicates the opposite. The default value is **false**.| 4547| write | boolean | No| Yes | Whether writing characteristics or descriptors is allowed.<br>**true** to enable, **false** otherwise. The default value is **true**.| 4548| writeEncrypted | boolean | No| Yes | Whether the characteristic or descriptor needs to be encrypted before being written.<br>The value **true** indicates that the characteristic or descriptor needs to be encrypted before being written, and the value **false** indicates the opposite. The default value is **false**.| 4549| writeEncryptedMitm | boolean | No| Yes | Whether the characteristic or descriptor to be written needs to be encrypted to prevent MITM attacks.<br>The value **true** means to enable encryption, and the value **false** indicates the opposite. The default value is **false**.| 4550| writeSigned | boolean | No| Yes | Whether the characteristic or descriptor needs to be signed before being written.<br>The value **true** means to enable encryption, and the value **false** indicates the opposite. The default value is **false**.| 4551| writeSignedMitm | boolean | No| Yes | Whether the characteristic or descriptor to be written needs to be signed to prevent MITM attacks.<br>The value **true** means to enable encryption, and the value **false** indicates the opposite. The default value is **false**.| 4552 4553 4554## GattWriteType 4555 4556Enumerates GATT characteristic write modes. 4557 4558**Atomic service API**: This API can be used in atomic services since API version 12. 4559 4560**System capability**: SystemCapability.Communication.Bluetooth.Core 4561 4562| Name | Value | Description | 4563| ------------------------------------| ------ | --------------- | 4564| WRITE | 1 | The peer Bluetooth device needs to send a confirmation after the write operation is complete. | 4565| WRITE_NO_RESPONSE | 2 | The peer Bluetooth device does ot need to send a confirmation after the write operation is complete. | 4566 4567 4568## ScanDuty 4569 4570Enumerates scan modes. 4571 4572**Atomic service API**: This API can be used in atomic services since API version 12. 4573 4574**System capability**: SystemCapability.Communication.Bluetooth.Core 4575 4576| Name | Value | Description | 4577| --------------------- | ---- | ------------ | 4578| SCAN_MODE_LOW_POWER | 0 | Low-power mode, which features lower power consumption but lower performance.| 4579| SCAN_MODE_BALANCED | 1 | Balanced mode, which features balanced performance and power consumption. | 4580| SCAN_MODE_LOW_LATENCY | 2 | Low-latency mode, which features high performance but high power consumption. | 4581 4582 4583## MatchMode 4584 4585Enumerates the hardware match modes of BLE scan filters. 4586 4587**Atomic service API**: This API can be used in atomic services since API version 12. 4588 4589**System capability**: SystemCapability.Communication.Bluetooth.Core 4590 4591| Name | Value | Description | 4592| --------------------- | ---- | ---------------------------------------- | 4593| MATCH_MODE_AGGRESSIVE | 1 | Reports advertising packets only if their signal strength is relatively low or they are transmitted sparsely within a short period of time.| 4594| MATCH_MODE_STICKY | 2 | Reports advertising packets only if their signal strength is high or they are transmitted intensively within a short period of time. | 4595 4596## AdvertisingState<sup>11+</sup> 4597 4598Enumerates BLE advertising states. 4599 4600**System capability**: SystemCapability.Communication.Bluetooth.Core 4601 4602| Name | Value | Description | 4603| -------- | ---- | ------------------------------ | 4604| STARTED<sup>11+</sup> | 1 | After [startAdvertising](#blestartadvertising11) is called, advertising is successfully started and related resources are allocated. | 4605| ENABLED<sup>11+</sup> | 2 | After [enableAdvertising](#bleenableadvertising11) is called, advertising is enabled successfully. | 4606| DISABLED<sup>11+</sup> | 3 | After [disableAdvertising](#bledisableadvertising11) is called, advertising is disabled successfully. | 4607| STOPPED<sup>11+</sup> | 4 | After [stopAdvertising](#blestopadvertising11) is called, advertising is disabled successfully and the resources allocated during initial advertising are released. | 4608 4609## PhyType<sup>12+</sup> 4610 4611Enumerates the physical channels that are used to receive BLE advertising packets. 4612 4613**Atomic service API**: This API can be used in atomic services since API version 12. 4614 4615**System capability**: SystemCapability.Communication.Bluetooth.Core 4616 4617| Name | Value | Description | 4618| -------- | ---- | ------------------------------ | 4619| PHY_LE_1M<sup>12+</sup> | 1 | 1M PHY type. | 4620| PHY_LE_ALL_SUPPORTED<sup>12+</sup> | 255 | All supported PHY types. | 4621 4622## ScanReport<sup>15+</sup> 4623 4624Defines the scan report. 4625 4626**Atomic service API**: This API can be used in atomic services since API version 15. 4627 4628**System capability**: SystemCapability.Communication.Bluetooth.Core 4629 4630| Name | Type |Read-Only |Optional | Description | 4631| --------- | ----------------------- | ---- | ---- | ------------------------------ | 4632| reportType | [ScanReportType](#scanreporttype15) | No| No| Type of the scan report. | 4633| scanResult | Array<[ScanResult](#scanresult)> | No| No| Scan result to be reported upon scanning advertising packets that meet the filter criteria. | 4634 4635## ScanReportType<sup>15+</sup> 4636 4637Enumerates scan report types. 4638 4639**System capability**: SystemCapability.Communication.Bluetooth.Core 4640 4641| Name | Value | Description | 4642| -------- | ---- | ------------------------------ | 4643| ON_FOUND | 1 | Triggers reporting when BLE advertising packets that meet the filter criteria are found. It applies to both the conventional and geofence reporting modes.<br> **Atomic service API**: This API can be used in atomic services since API version 15. | 4644| ON_LOST | 2 | Triggers reporting when no BLE advertising packets that meet the filter criteria are found. It applies only to the geofence reporting mode.<br> **Atomic service API**: This API can be used in atomic services since API version 15. | 4645| ON_BATCH<sup>19+</sup> | 3 | Triggers reporting when BLE advertising packets that meet the filter criteria are found. The reporting interval is the value of **interval** in [ScanOptions](#scanoptions).<br> **Atomic service API**: This API can be used in atomic services since API version 19. | 4646 4647## ScanReportMode<sup>15+</sup> 4648 4649Enumerates scan result reporting modes. 4650 4651**System capability**: SystemCapability.Communication.Bluetooth.Core 4652 4653| Name | Value | Description | 4654| -------- | ---- | ------------------------------ | 4655| NORMAL | 1 | Conventional reporting mode. The BLE advertising packets that meet the filter criteria are reported immediately after being scanned.<br>**Atomic service API**: This API can be used in atomic services since API version 15. | 4656| BATCH<sup>19+</sup> | 2 | Batch scan reporting mode.<br>- This mode reduces the frequency at which scan results are reported, enabling the system to remain in sleep mode for extended periods and thus reducing the overall power consumption of the device.<br>- In this mode, the BLE advertising packets that meet the filtering criteria are not reported immediately. Instead, they are reported after being cached for a period of time (specified by **interval** in [ScanOptions](#scanoptions)).<br>**Atomic service API**: This API can be used in atomic services since API version 19. | 4657| FENCE_SENSITIVITY_LOW<sup>18+</sup> | 10 | Low-sensitivity geofence reporting mode.<br>- In this mode, advertising packets are reported only when the device enters or leaves the geofence.<br>- This mode is applicable when the signal strength is relatively high and advertising packets are transmitted sparsely within a short period of time.<br>- When advertising packets are detected for the first time, the device enters the geofence and reporting is triggered once.<br>- If no advertising packets are detected within the specified period of time, the device leaves the geofence and reporting is triggered once.<br>**Atomic service API**: This API can be used in atomic services since API version 18. | 4658| FENCE_SENSITIVITY_HIGH<sup>18+</sup> | 11 | High-sensitivity geofence reporting mode.<br>- In this mode, advertising packets are reported only when the device enters or leaves the geofence.<br>- This mode is applicable when the signal strength is relatively low and advertising packets are transmitted sparsely within a short period of time.<br>- When advertising packets are detected for the first time, the device enters the geofence and reporting is triggered once.<br>- If no advertising packets are detected within the specified period of time, the device leaves the geofence and reporting is triggered once.<br>**Atomic service API**: This API can be used in atomic services since API version 18. | 4659