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