> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** > The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. > > The Bluetooth module provides Classic Bluetooth capabilities and Bluetooth Low Energy (BLE) scan and advertising. ## Modules to Import ``` import bluetooth from '@ohos.bluetooth'; ``` ## Required Permissions ohos.permission.USE_BLUETOOTH ohos.permission.MANAGE_BLUETOOTH ohos.permission.DISCOVER_BLUETOOTH ohos.permission.LOCATION ## bluetooth.enableBluetooth enableBluetooth(): boolean Enables Bluetooth. **Return values:** | Type | Description | | -------- | -------- | | boolean | Returns **true** if Bluetooth is enabled; returns **false** otherwise. | **Example:** ``` let enable = bluetooth.enableBluetooth(); ``` ## bluetooth.disableBluetooth disableBluetooth(): boolean Disables Bluetooth. **Return values:** | Type | Description | | -------- | -------- | | boolean | Returns **true** if Bluetooth is disabled; returns **false** otherwise. | **Example:** ``` let disable = bluetooth.disableBluetooth(); ``` ## bluetooth.getLocalName getLocalName(): string Obtains the name of the local Bluetooth device. **Return values:** | Type | Description | | -------- | -------- | | string | Name of the local Bluetooth device. | **Example:** ``` let localName = bluetooth.getLocalName(); ``` ## bluetooth.getState getState(): BluetoothState Obtains the Bluetooth state. **Return values:** | Type | Description | | -------- | -------- | | [BluetoothState](#bluetoothstate) | Bluetooth state obtained. | **Example:** ``` let state = bluetooth.getState(); ``` ## bluetooth.getBtConnectionState getBtConnectionState(): ProfileConnectionState Obtains the profile connection state of this Bluetooth device. **Return values:** | Type | Description | | -------- | -------- | | [ProfileConnectionState](#profileconnectionstate) | Profile connection state obtained. | **Example:** ``` let connectionState = bluetooth.getBtConnectionState(); ``` ## bluetooth.setLocalName setLocalName(name: string): boolean Sets the name of the local Bluetooth device. **Parameters:** | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | | name | string | Yes | Bluetooth device name to be set. It cannot exceed 128 characters. | **Return values:** | Type | Description | | -------- | -------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise. | **Example:** ``` let ret = bluetooth.setLocalName('device_name'); ``` ## bluetooth.pairDevice pairDevice(deviceId: string): boolean Initiates Bluetooth pairing. **Parameters:** | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | | deviceId | string | Yes | Address of the peer device to pair, for example, **8F:8F:8E:8E:6D:6D**. | **Return values:** | Type | Description | | -------- | -------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise. | **Example:** ``` // The actual address can be scanned. let result = bluetooth.pairDevice("8F:8F:8E:8E:6D:6D"); ``` ## bluetooth.getPairedDevices getPairedDevices(): Array<string> Obtains the Bluetooth pairing list. **Return values:** | Type | Description | | -------- | -------- | | Array<string> | List of the addresses of the paired Bluetooth devices. | **Example:** ``` let devices = bluetooth.getPairedDevices(); ``` ## bluetooth.setBluetoothScanMode setBluetoothScanMode(mode: ScanMode, duration: number): boolean Sets the Bluetooth scan mode so that the device can be discovered by a peer device. **Parameters:** | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | | mode | [ScanMode](#scanmode) | Yes | Bluetooth scan mode. | | duration | number | Yes | Duration (in seconds) in which the device can be discovered. The value **0** indicates unlimited time. | **Return values:** | Type | Description | | -------- | -------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise. | **Example:** ``` // The device can be discovered and connected only when the discoverable and connectable mode is used. let result = bluetooth.setBluetoothScanMode(ScanMode.SCAN_MODE_CONNECTABLE_GENERAL_DISCOVERABLE, 100); ``` ## bluetooth.getBluetoothScanMode getBluetoothScanMode(): ScanMode Obtains the Bluetooth scan mode. **Return values:** | Type | Description | | -------- | -------- | | [ScanMode](#scanmode) | Bluetooth scan mode obtained. | **Example:** ``` let scanMode = bluetooth.getBluetoothScanMode(); ``` ## bluetooth.startBluetoothDiscovery startBluetoothDiscovery(): boolean Starts Bluetooth scan to discover peer devices. **Return values:** | Type | Description | | -------- | -------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise. | **Example:** ``` let deviceId; function onReceiveEvent(data) { deviceId = data; } bluetooth.on('bluetoothDeviceFind', onReceiveEvent); let result = bluetooth.startBluetoothDiscovery(); ``` ## bluetooth.stopBluetoothDiscovery stopBluetoothDiscovery(): boolean Stops Bluetooth scan. **Return values:** | Type | Description | | -------- | -------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise. | **Example:** ``` let result = bluetooth.stopBluetoothDiscovery(); ``` ## bluetooth.setDevicePairingConfirmation setDevicePairingConfirmation(device: string, accept: boolean): boolean Sets the device pairing confirmation. **Parameters:** | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | | device | string | Yes | Address of the peer device, for example, **8F:8F:8E:8E:6D:6D**. | | accept | boolean | Yes | Whether to accept the pairing request. The value **true** means to accept the pairing request, and the value **false** means the opposite. | **Return values:** | Type | Description | | -------- | -------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise. | **Example:** ``` // Subscribe to the pinRequired event and configure the pairing confirmation after receiving a pairing request from the peer device. function onReceivePinRequiredEvent(data) { // data is the input parameter for the pairing request. console.info('pin required = '+ JSON.stringify(data)); bluetooth.setDevicePairingConfirmation(data.deviceId, true); } bluetooth.on("pinRequired", onReceivePinRequiredEvent); ``` ## bluetooth.on('bluetoothDeviceFind') on(type: "bluetoothDeviceFind", callback: Callback<Array<string>>): void Subscribes to the Bluetooth device discovery events. **Parameters:** | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | | type | string | Yes | Event type. The value **bluetoothDeviceFind** indicates an event reported when a Bluetooth device is discovered. | | callback | Callback<Array<string>> | Yes | Callback invoked to return the discovered devices. You need to implement this callback. | **Return values:** None. **Example:** ``` function onReceiveEvent(data) { // data is a set of Bluetooth device addresses. console.info('bluetooth device find = '+ JSON.stringify(data)); } bluetooth.on('bluetoothDeviceFind', onReceiveEvent); ``` ## bluetooth.off('bluetoothDeviceFind') off(type: "bluetoothDeviceFind", callback?: Callback<Array<string>>): void Unsubscribes from the Bluetooth device discovery events. **Parameters:** | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | | type | string | Yes | Event type. The value **bluetoothDeviceFind** indicates an event reported when a Bluetooth device is discovered. | | callback | Callback<Array<string>> | No | Callback used to report the discovered devices. If this parameter is not set, this method unsubscribes from all callbacks corresponding to **type**. | **Return values:** None. **Example:** ``` function onReceiveEvent(data) { console.info('bluetooth device find = '+ JSON.stringify(data)); } bluetooth.on('bluetoothDeviceFind', onReceiveEvent); bluetooth.off('bluetoothDeviceFind', onReceiveEvent); ``` ## bluetooth.on('pinRequired') on(type: "pinRequired", callback: Callback<PinRequiredParam>): void Subscribes to the pairing request events of the peer Bluetooth device. **Parameters:** | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | | type | string | Yes | Event type. The value **pinRequired** indicates a pairing request event. | | callback | Callback<[PinRequiredParam](#pinrequiredparam)> | Yes | Callback invoked to return the pairing request. You need to implement this callback. | **Return values:** None. **Example:** ``` function onReceiveEvent(data) { // data is the pairing request parameter. console.info('pin required = '+ JSON.stringify(data)); } bluetooth.on('pinRequired', onReceiveEvent); ``` ## bluetooth.off('pinRequired') off(type: "pinRequired", callback?: Callback<PinRequiredParam>): void Unsubscribes from the pairing request events of the peer Bluetooth device. **Parameters:** | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | | type | string | Yes | Event type. The value **pinRequired** indicates a pairing request event. | | callback | Callback<[PinRequiredParam](#pinrequiredparam)> | No | Callback used to report the Bluetooth pairing request. The input parameter is the pairing request parameter. If this parameter is not set, this method unsubscribes from all callbacks corresponding to **type**. | **Return values:** None. **Example:** ``` function onReceiveEvent(data) { console.info('pin required = '+ JSON.stringify(data)); } bluetooth.on('pinRequired', onReceiveEvent); bluetooth.off('pinRequired', onReceiveEvent); ``` ## bluetooth.on('bondStateChange') on(type: "bondStateChange", callback: Callback<BondState>): void Subscribes to the Bluetooth pairing state change events. **Parameters:** | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | | type | string | Yes | Event type. The value **bondStateChange** indicates a Bluetooth pairing state change event. | | callback | Callback<[BondState](#bondstate)> | Yes | Callback invoked to return the pairing state. You need to implement this callback. | **Return values:** None. **Example:** ``` function onReceiveEvent(data) { // data, as the input parameter of the callback, indicates the pairing state. console.info('pair state = '+ JSON.stringify(data)); } bluetooth.on('bondStateChange', onReceiveEvent); ``` ## bluetooth.off('bondStateChange') off(type: "bondStateChange", callback?: Callback<BondState>): void Unsubscribes from the Bluetooth pairing state change events. **Parameters:** | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | | type | string | Yes | Event type. The value **bondStateChange** indicates a Bluetooth pairing state change event. | | callback | Callback<[BondState](#bondstate)> | No | Callback used to report the change of the Bluetooth pairing state. If this parameter is not set, this method unsubscribes from all callbacks corresponding to **type**. | **Return values:** None. **Example:** ``` function onReceiveEvent(data) { console.info('bond state = '+ JSON.stringify(data)); } bluetooth.on('bondStateChange', onReceiveEvent); bluetooth.off('bondStateChange', onReceiveEvent); ``` ## bluetooth.on('stateChange') on(type: "stateChange", callback: Callback<BluetoothState>): void Subscribes to the Bluetooth connection state change events. **Parameters:** | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | | type | string | Yes | Event type. The value **stateChange** indicates a Bluetooth connection state change event. | | callback | Callback<[BluetoothState](#bluetoothstate)> | Yes | Callback invoked to return the Bluetooth connection state. You need to implement this callback. | **Return values:** None. **Example:** ``` function onReceiveEvent(data) { console.info('bluetooth state = '+ JSON.stringify(data)); } bluetooth.on('stateChange', onReceiveEvent); ``` ## bluetooth.off('stateChange') off(type: "stateChange", callback?: Callback<BluetoothState>): void Unsubscribes from the Bluetooth connection state change events. **Parameters:** | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | | type | string | Yes | Event type. The value **stateChange** indicates a Bluetooth connection state change event. | | callback | Callback<[BluetoothState](#bluetoothstate)> | No | Callback used to report the Bluetooth connection state. If this parameter is not set, this method unsubscribes from all callbacks corresponding to **type**. | **Return values:** None. **Example:** ``` function onReceiveEvent(data) { console.info('bluetooth state = '+ JSON.stringify(data)); } bluetooth.on('stateChange', onReceiveEvent); bluetooth.off('stateChange', onReceiveEvent); ``` ## bluetooth.sppListen sppListen(name: string, option: SppOption, callback: AsyncCallback<number>): void Creates a server listening socket. **Parameters:** | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | | name | string | Yes | Service name. | | option | [SppOption](#sppoption) | Yes | Serial port profile (SPP) listening configuration. | | callback | AsyncCallback<number> | Yes | Callback invoked to return the server socket ID. | **Example:** ``` let serverNumber = -1; function serverSocket(code, number) { console.log('bluetooth error code: ' + code.code); if (code.code == 0) { console.log('bluetooth serverSocket Number: ' + number); serverNumber = number; } } let sppOption = {uuid: '00001810-0000-1000-8000-00805F9B34FB', secure: false, type: 0}; bluetooth.sppListen('server1', sppOption, serverSocket); ``` ## bluetooth.sppAccept sppAccept(serverSocket: number, callback: AsyncCallback<number>): void Listens for a connection to be made to this socket from the client and accepts it. **Parameters:** | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | | serverSocket | number | Yes | Server socket ID. | | callback | AsyncCallback<number> | Yes | Callback invoked to return the client socket ID. | **Example:** ``` let clientNumber = -1; function acceptClientSocket(code, number) { console.log('bluetooth error code: ' + code.code); if (code.code == 0) { console.log('bluetooth clientSocket Number: ' + number); // The obtained clientNumber is used as the socket ID for subsequent read/write operations on the server. clientNumber = number; } } bluetooth.sppAccept(serverNumber, acceptClientSocket); ``` ## bluetooth.sppConnect sppConnect(device: string, option: SppOption, callback: AsyncCallback<number>): void Initiates an SPP connection to a peer device from the client. **Parameters:** | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | | device | string | Yes | Address of the peer device, for example, **8F:8F:8E:8E:6D:6D**. | | option | [SppOption](#sppoption) | Yes | Configuration for connecting to the SPP client. | | callback | AsyncCallback<number> | Yes | Callback invoked to return the client socket ID. | **Example:** ``` let clientNumber = -1; function clientSocket(code, number) { if (code.code != 0) { return; } console.log('bluetooth serverSocket Number: ' + number); // The obtained clientNumber is used as the socket ID for subsequent read/write operations on the client. clientNumber = number; } let sppOption = {uuid: '00001810-0000-1000-8000-00805F9B34FB', secure: false, type: 0}; bluetooth.sppConnect('8F:8F:8E:8E:6D:6D', sppOption, clientSocket); ``` ## bluetooth.sppCloseServerSocket sppCloseServerSocket(socket: number): void Closes the listening socket of the server. **Parameters:** | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | | socket | number | Yes | ID of the listening socket on the server. The ID is obtained by **sppListen**. | **Example:** ``` bluetooth.sppCloseServerSocket(serverNumber); ``` ## bluetooth.sppCloseClientSocket sppCloseClientSocket(socket: number): void Closes the client socket. **Parameters:** | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | | socket | number | Yes | Client socket ID, which is obtained by **sppAccept** or **sppConnect**. | **Example:** ``` bluetooth.sppCloseClientSocket(clientNumber); ``` ## bluetooth.sppWrite sppWrite(clientSocket: number, data: ArrayBuffer): boolean Writes data to the peer device through the socket. **Parameters:** | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | | clientSocket | number | Yes | Client socket ID, which is obtained by **sppAccept** or **sppConnect**. | | data | ArrayBuffer | Yes | Data to write. | **Return values:** | Type | Description | | -------- | -------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise. | **Example:** ``` let arrayBuffer = new ArrayBuffer(8); let data = new Uint8Array(arrayBuffer); data[0] = 123; let ret = bluetooth.sppWrite(clientNumber, arrayBuffer); if (ret) { console.log('spp write successfully'); } else { console.log('spp write failed'); } ``` ## bluetooth.on('sppRead') on(type: "sppRead", clientSocket: number, callback: Callback<ArrayBuffer>): void Subscribes to the SPP read request events. **Parameters:** | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | | type | string | Yes | Event type. The value **sppRead** indicates an SPP read request event. | | clientSocket | number | Yes | Client socket ID, which is obtained by **sppAccept** or **sppConnect**. | | callback | Callback<ArrayBuffer> | Yes | Callback invoked to return the data read. | **Return values:** None. **Example:** ``` function dataRead(dataBuffer) { let data = new Uint8Array(dataBuffer); console.log('bluetooth data is: ' + data[0]); } bluetooth.on('sppRead', clientNumber, dataRead); ``` ## bluetooth.off('sppRead') off(type: "sppRead", clientSocket: number, callback?: Callback<ArrayBuffer>): void Unsubscribes from the SPP read request events. **Parameters:** | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | | type | string | Yes | Event type. The value **sppRead** indicates an SPP read request event. | | clientSocket | number | Yes | Client socket ID, which is obtained by **sppAccept** or **sppConnect**. | | callback | Callback<ArrayBuffer> | No | Callback used to report an SPP read request event. If this parameter is not set, this method unsubscribes from all callbacks corresponding to **type**. | **Return values:** None. **Example:** ``` bluetooth.off('sppRead', clientNumber); ``` ## bluetooth.BLE ### bluetooth.BLE.createGattServer createGattServer(): GattServer Creates a **GattServer** instance. **Return values:** | Type | Description | | -------- | -------- | | [GattServer](#gattserver) | **GattServer** instance created. Before using a method of the server, you must create a **GattSever** instance. | **Example:** ``` let gattServer = bluetooth.BLE.createGattServer(); ``` ### bluetooth.BLE.createGattClientDevice createGattClientDevice(deviceId: string): GattClientDevice Creates a **GattClientDevice** instance. **Parameters:** | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | | deviceId | string | Yes | Address of the peer device, for example, **8F:8F:8E:8E:6D:6D**. | **Return values:** | Type | Description | | -------- | -------- | | [GattClientDevice](#gattclientdevice) | **GattClientDevice** instance created. Before using a method of the client, you must create a **GattClientDevice** instance. | **Example:** ``` let device = bluetooth.BLE.createGattClientDevice('8F:8F:8E:8E:6D:6D'); ``` ### bluetooth.BLE.getConnectedBLEDevices getConnectedBLEDevices(): Array<string> Obtains the BLE devices connected to this device. **Return values:** | Type | Description | | -------- | -------- | | Array<string> | Addresses of the BLE devices connected to this device. | **Example:** ``` let result = bluetooth.BLE.getConnectedBLEDevices(); ``` ### bluetooth.BLE.startBLEScan startBLEScan(filters: Array<ScanFilter>, options?: ScanOptions): void Starts a BLE scan. **Parameters:** | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | | filters | Array<[ScanFilter](#scanfilter)> | Yes | Criteria for filtering the scan result. Set this parameter to **null** if you do not want to filter the scan result. | | options | [ScanOptions](#scanoptions) | No | Scan options. | **Return values:** None. **Example:** ``` function onReceiveEvent(data) { console.info('BLE scan device find result = '+ JSON.stringify(data)); } bluetooth.BLE.on("BLEDeviceFind", onReceiveEvent); bluetooth.BLE.startBLEScan( [{ deviceId:"8F:8F:8E:8E:6D:6D", name:"test", serviceUuid:"00001888-0000-1000-8000-00805f9b34fb" }], { interval: 500, dutyMode: bluetooth.ScanDuty.SCAN_MODE_LOW_POWER, matchMode: bluetooth.MatchMode.MATCH_MODE_AGGRESSIVE, } ); ``` ### bluetooth.BLE.stopBLEScan stopBLEScan(): void Stops the BLE scan. **Return values:** None. **Example:** ``` bluetooth.BLE.stopBLEScan(); ``` ### bluetooth.BLE.on('BLEDeviceFind') on(type: "BLEDeviceFind", callback: Callback<Array<ScanResult>>): void Subscribe to the BLE device discovery events. **Parameters:** | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | | type | string | Yes | Event type. The value **BLEDeviceFind** indicates an event reported when a BLE device is discovered. | | callback | Callback<Array<[ScanResult](#scanresult)>> | Yes | Callback invoked to return the discovered devices. You need to implement this callback. | **Return values:** None. **Example:** ``` function onReceiveEvent(data) { console.info('bluetooth device find = '+ JSON.stringify(data)); } bluetooth.BLE.on('BLEDeviceFind', onReceiveEvent); ``` ### bluetooth.BLE.off('BLEDeviceFind') off(type: "BLEDeviceFind", callback?: Callback<Array<ScanResult>>): void Unsubscribes from the BLE device discovery events. **Parameters:** | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | | type | string | Yes | Event type. The value **BLEDeviceFind** indicates an event reported when a BLE device is discovered. | | callback | Callback<Array<[ScanResult](#scanresult)>> | No | Callback used to report the discovered devices. If this parameter is not set, this method unsubscribes from all callbacks corresponding to **type**. | **Return values:** None. **Example:** ``` function onReceiveEvent(data) { console.info('bluetooth device find = '+ JSON.stringify(data)); } bluetooth.BLE.on('BLEDeviceFind', onReceiveEvent); bluetooth.BLE.off('BLEDeviceFind', onReceiveEvent); ``` ## GattServer Implements the Generic Attribute Profile (GATT) server. Before using a method of this class, you need to create a **GattServer** instance using the **createGattServer()** method. ### startAdvertising startAdvertising(setting: AdvertiseSetting, advData: AdvertiseData, advResponse?: AdvertiseData): void Starts BLE advertising. **Parameters:** | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | | setting | [AdvertiseSetting](#advertisesetting) | Yes | Settings related to BLE advertising. | | advData | [AdvertiseData](#advertisedata) | Yes | Content of the BLE advertisement packet. | | advResponse | [AdvertiseData](#advertisedata) | No | Response to the BLE scan request. | **Return values:** None. **Example:** ``` let manufactureValueBuffer = new Uint8Array(4); manufactureValueBuffer[0] = 1; manufactureValueBuffer[1] = 2; manufactureValueBuffer[2] = 3; manufactureValueBuffer[3] = 4; let serviceValueBuffer = new Uint8Array(4); serviceValueBuffer[0] = 4; serviceValueBuffer[1] = 6; serviceValueBuffer[2] = 7; serviceValueBuffer[3] = 8; console.info('manufactureValueBuffer = '+ JSON.stringify(manufactureValueBuffer)); console.info('serviceValueBuffer = '+ JSON.stringify(serviceValueBuffer)); let gattServer = bluetooth.BLE.createGattServer(); gattServer.startAdvertising({ interval:150, txPower:60, connectable:true, },{ serviceUuids:["00001888-0000-1000-8000-00805f9b34fb"], manufactureData:[{ manufactureId:4567, manufactureValue:manufactureValueBuffer.buffer }], serviceData:[{ serviceUuid:"00001888-0000-1000-8000-00805f9b34fb", serviceValue:serviceValueBuffer.buffer }], },{ serviceUuids:["00001889-0000-1000-8000-00805f9b34fb"], manufactureData:[{ manufactureId:1789, manufactureValue:manufactureValueBuffer.buffer }], serviceData:[{ serviceUuid:"00001889-0000-1000-8000-00805f9b34fb", serviceValue:serviceValueBuffer.buffer }], }); ``` ### stopAdvertising stopAdvertising(): void Stops BLE advertising. **Return values:** None. **Example:** ``` let server = bluetooth.BLE.createGattServer(); server.stopAdvertising(); ``` ### addService addService(service: GattService): boolean Adds a service to this GATT server. **Parameters:** | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | | service | [GattService](#gattservice) | Yes | Service to add. | **Return values:** | Type | Description | | -------- | -------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise. | **Example:** ``` // Create descriptors. let descriptors = []; let arrayBuffer = new ArrayBuffer(8); let descV = new Uint8Array(arrayBuffer); descV[0] = 11; let descriptor = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', descriptorUuid: '00001830-0000-1000-8000-00805F9B34FB', descriptorValue: arrayBuffer}; descriptors[0] = descriptor; // Create characteristics. let characteristics = []; let arrayBufferC = new ArrayBuffer(8); let cccV = new Uint8Array(arrayBufferC); cccV[0] = 1; let characteristic = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', characteristicValue: arrayBufferC, descriptors:descriptors}; let characteristicN = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', characteristicUuid: '00001821-0000-1000-8000-00805F9B34FB', characteristicValue: arrayBufferC, descriptors:descriptorsN}; characteristics[0] = characteristic; // Create a gattService instance. let gattService = {serviceUuid:'00001810-0000-1000-8000-00805F9B34FB', isPrimary: true, characteristics:characteristics, includeServices:[]}; let gattServer = bluetooth.BLE.createGattServer(); let ret = gattServer.addService(gattService); if (ret) { console.log("add service successfully"); } else { console.log("add service failed"); } ``` ### removeService removeService(serviceUuid: string): boolean Removes a service from this GATT server. **Parameters:** | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | | serviceUuid | string | Yes | Universally unique identifier (UUID) of the service to remove, for example, **00001810-0000-1000-8000-00805F9B34FB**. | **Return values:** | Type | Description | | -------- | -------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise. | **Example:** ``` let server = bluetooth.BLE.createGattServer(); server.removeService('00001810-0000-1000-8000-00805F9B34FB'); ``` ### close close(): void Closes this GATT server to unregister it from the protocol stack. After this method is called, this [GattServer](#gattserver) instance cannot be used. **Example:** ``` let server = bluetooth.BLE.createGattServer(); server.close(); ``` ### notifyCharacteristicChanged notifyCharacteristicChanged(deviceId: string, notifyCharacteristic: NotifyCharacteristic): boolean Notifies the connected client device when a characteristic value changes. **Parameters:** | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | | deviceId | string | Yes | Address of the client device to notify, for example, **8F:8F:8E:8E:6D:6D**. | | notifyCharacteristic | [NotifyCharacteristic](#notifycharacteristic) | Yes | New characteristic value. | **Return values:** | Type | Description | | -------- | -------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise. | **Example:** ``` let notifyCharacteristic = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', characteristicUuid: '00001821-0000-1000-8000-00805F9B34FB', characteristicValue: notifyCcc.characteristicValue, confirm: false}; let server = bluetooth.BLE.createGattServer(); server.notifyCharacteristicChanged('8F:8F:8E:8E:6D:6D', notifyCharacteristic); ``` ### sendResponse sendResponse(serverResponse: ServerResponse): boolean Sends a response to a read or write request from the GATT client. **Parameters:** | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | | serverResponse | [ServerResponse](#serverresponse) | Yes | Response returned by the GATT server. | **Return values:** | Type | Description | | -------- | -------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise. | **Example:** ``` /* Send a response. */ let arrayBufferCCC = new ArrayBuffer(8); let cccValue = new Uint8Array(arrayBufferCCC); cccValue[0] = 1123; let serverResponse = { "deviceId": "8F:8F:8E:8E:6D:6D", "transId": 0, "status": 0, "offset": 0, "value": arrayBufferCCC, }; let gattServer = bluetooth.BLE.createGattServer(); let ret = gattServer.sendResponse(serverResponse); if (ret) { console.log('bluetooth sendResponse successfully'); } else { console.log('bluetooth sendResponse failed'); } ``` ### on('characteristicRead') on(type: "characteristicRead", callback: Callback<CharacteristicReadReq>): void Subscribes to the characteristic read request events. **Parameters:** | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | | type | string | Yes | Event type. The value **characteristicRead** indicates a characteristic read request event. | | callback | Callback<[CharacteristicReadReq](#characteristicreadreq)> | Yes | Callback invoked to return a characteristic read request from the GATT client. | **Return values:** None. **Example:** ``` let arrayBufferCCC = new ArrayBuffer(8); let cccValue = new Uint8Array(arrayBufferCCC); cccValue[0] = 1123; function ReadCharacteristicReq(CharacteristicReadReq) { let deviceId = CharacteristicReadReq.deviceId; let transId = CharacteristicReadReq.transId; let offset = CharacteristicReadReq.offset; let characteristicUuid = CharacteristicReadReq.characteristicUuid; let serverResponse = {deviceId: deviceId, transId: transId, status: 0, offset: offset, value:arrayBufferCCC}; let ret = gattServer.sendResponse(serverResponse); if (ret) { console.log('bluetooth sendResponse successfully'); } else { console.log('bluetooth sendResponse failed'); } } let gattServer = bluetooth.BLE.createGattServer(); gattServer.on("characteristicRead", ReadCharacteristicReq); ``` ### off('characteristicRead') off(type: "characteristicRead", callback?: Callback<CharacteristicReadReq>): void Unsubscribes from the characteristic read request events. **Parameters:** | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | | type | string | Yes | Event type. The value **characteristicRead** indicates a characteristic read request event. | | callback | Callback<[CharacteristicReadReq](#characteristicreadreq)> | No | Callback used to report a characteristic read request event. If this parameter is not set, this method unsubscribes from all callbacks corresponding to **type**. | **Return values:** None. **Example:** ``` let gattServer = bluetooth.BLE.createGattServer(); gattServer.off("characteristicRead"); ``` ### on('characteristicWrite') on(type: "characteristicWrite", callback: Callback<CharacteristicWriteReq>): void Subscribes to the characteristic write request events. **Parameters:** | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | | type | string | Yes | Event type. The value **characteristicWrite** indicates a characteristic write request event. | | callback | Callback<[DescriptorWriteReq](#descriptorwritereq)> | Yes | Callback invoked to return a characteristic write request from the GATT client. | **Return values:** None. **Example:** ``` let arrayBufferCCC = new ArrayBuffer(8); let cccValue = new Uint8Array(arrayBufferCCC); function WriteCharacteristicReq(CharacteristicWriteReq) { let deviceId = CharacteristicWriteReq.deviceId; let transId = CharacteristicWriteReq.transId; let offset = CharacteristicWriteReq.offset; let isPrep = CharacteristicWriteReq.isPrep; let needRsp = CharacteristicWriteReq.needRsp; let value = new Uint8Array(CharacteristicWriteReq.value); let characteristicUuid = CharacteristicWriteReq.characteristicUuid; cccValue[0] = value[0]; let serverResponse = {deviceId: deviceId, transId: transId, status: 0, offset: offset, value:arrayBufferCCC}; let ret = gattServer.sendResponse(serverResponse); if (ret) { console.log('bluetooth sendResponse successfully'); } else { console.log('bluetooth sendResponse failed'); } } let gattServer = bluetooth.BLE.createGattServer(); gattServer.on("characteristicWrite", WriteCharacteristicReq); ``` ### off('characteristicWrite') off(type: "characteristicWrite", callback?: Callback<CharacteristicWriteReq>): void Unsubscribes from the characteristic write request events. **Parameters:** | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | | type | string | Yes | Event type. The value **characteristicWrite** indicates a characteristic write request event. | | callback | Callback<[CharacteristicWriteReq](#characteristicwritereq)> | No | Callback used to report a characteristic write request event. If this parameter is not set, this method unsubscribes from all callbacks corresponding to **type**. | **Return values:** None. **Example:** ``` let gattServer = bluetooth.BLE.createGattServer(); gattServer.off("characteristicWrite"); ``` ### on('descriptorRead') on(type: "descriptorRead", callback: Callback<DescriptorReadReq>): void Subscribes to the descriptor read request events. **Parameters:** | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | | type | string | Yes | Event type. The value **descriptorRead** indicates a descriptor read request event. | | callback | Callback<[DescriptorReadReq](#descriptorreadreq)> | Yes | Callback invoked to return a descriptor read request from the GATT client. | **Return values:** None. **Example:** ``` let arrayBufferDesc = new ArrayBuffer(8); let descValue = new Uint8Array(arrayBufferDesc); descValue[0] = 1101; function ReadDescriptorReq(DescriptorReadReq) { let deviceId = DescriptorReadReq.deviceId; let transId = DescriptorReadReq.transId; let offset = DescriptorReadReq.offset; let descriptorUuid = DescriptorReadReq.descriptorUuid; let serverResponse = {deviceId: deviceId, transId: transId, status: 0, offset: offset, value:arrayBufferDesc}; let ret = gattServer.sendResponse(serverResponse); if (ret) { console.log('bluetooth sendResponse successfully'); } else { console.log('bluetooth sendResponse failed'); } } let gattServer = bluetooth.BLE.createGattServer(); gattServer.on("descriptorRead", ReadDescriptorReq); ``` ### off('descriptorRead') off(type: "descriptorRead", callback?: Callback<DescriptorReadReq>): void Unsubscribes from the descriptor read request events. **Parameters:** | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | | type | string | Yes | Event type. The value **descriptorRead** indicates a descriptor read request event. | | callback | Callback<[DescriptorReadReq](#descriptorreadreq)> | No | Callback used to report a descriptor read request event. If this parameter is not set, this method unsubscribes from all callbacks corresponding to **type**. | **Return values:** None. **Example:** ``` let gattServer = bluetooth.BLE.createGattServer(); gattServer.off("descriptorRead"); ``` ### on('descriptorWrite') on(type: "descriptorWrite", callback: Callback<DescriptorWriteReq>): void Subscribes to the descriptor write request events. **Parameters:** | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | | type | string | Yes | Event type. The value **descriptorWrite** indicates a descriptor write request event. | | callback | Callback<[DescriptorWriteReq](#descriptorwritereq)> | Yes | Callback invoked to return a descriptor write request from the GATT client. | **Return values:** None. **Example:** ``` let arrayBufferDesc = new ArrayBuffer(8); let descValue = new Uint8Array(arrayBufferDesc); function WriteDescriptorReq(DescriptorWriteReq) { let deviceId = DescriptorWriteReq.deviceId; let transId = DescriptorWriteReq.transId; let offset = DescriptorWriteReq.offset; let isPrep = DescriptorWriteReq.isPrep; let needRsp = DescriptorWriteReq.needRsp; let value = new Uint8Array(DescriptorWriteReq.value); let descriptorUuid = DescriptorWriteReq.descriptorUuid; descValue[0] = value[0]; let serverResponse = {deviceId: deviceId, transId: transId, status: 0, offset: offset, value:arrayBufferDesc}; let ret = gattServer.sendResponse(serverResponse); if (ret) { console.log('bluetooth sendResponse successfully'); } else { console.log('bluetooth sendResponse failed'); } } let gattServer = bluetooth.BLE.createGattServer(); gattServer.on("descriptorRead", WriteDescriptorReq); ``` ### off('descriptorWrite') off(type: "descriptorWrite", callback?: Callback<DescriptorWriteReq>): void Unsubscribes from the descriptor write request events. **Parameters:** | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | | type | string | Yes | Event type. The value **descriptorWrite** indicates a descriptor write request event. | | callback | Callback<[DescriptorWriteReq](#descriptorwritereq)> | No | Callback used to report a descriptor read request event. If this parameter is not set, this method unsubscribes from all callbacks corresponding to **type**. | **Return values:** None. **Example:** ``` let gattServer = bluetooth.BLE.createGattServer(); gattServer.off("descriptorWrite"); ``` ### on('connectStateChange') on(type: "connectStateChange", callback: Callback<BLEConnectChangedState>): void Subscribes to the BLE connection state change events. **Parameters:** | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | | type | string | Yes | Event type. The value **connectStateChange** indicates a BLE connection state change event. | | callback | Callback<[BLEConnectChangedState](#bleconnectchangedstate)> | Yes | Callback invoked to return the BLE connection state. | **Return values:** None. **Example:** ``` function Connected(BLEConnectChangedState) { let deviceId = BLEConnectChangedState.deviceId; let status = BLEConnectChangedState.state; } let gattServer = bluetooth.BLE.createGattServer(); gattServer.on("connectStateChange", Connected); ``` ### off('connectStateChange') off(type: "connectStateChange", callback?: Callback<BLEConnectChangedState>): void Unsubscribes from the BLE connection state change events. **Parameters:** | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | | type | string | Yes | Event type. The value **connectStateChange** indicates a BLE connection state change event. | | callback | Callback<[BLEConnectChangedState](#bleconnectchangedstate)> | No | Callback used to report the BLE connection state. If this parameter is not set, this method unsubscribes from all callbacks corresponding to **type**. | **Return values:** None. **Example:** ``` let gattServer = bluetooth.BLE.createGattServer(); gattServer.off("connectStateChange"); ``` ## GattClientDevice Implements the GATT client. Before using a method of this class, you must create a **GattClientDevice** instance using the **createGattClientDevice(deviceId: string)** method. ### connect connect(): boolean Initiates a connection to the peer BLE device. **Return values:** | Type | Description | | -------- | -------- | | boolean | Returns **true** if the connection is successful; returns **false** otherwise. | **Example:** ``` let device = bluetooth.BLE.createGattClientDevice('8F:8F:8E:8E:6D:6D'); let ret = device.connect(); ``` ### disconnect disconnect(): boolean Disconnects from the peer BLE device. **Return values:** | Type | Description | | -------- | -------- | | boolean | Returns **true** if the connection is successful; returns **false** otherwise. | **Example:** ``` let device = bluetooth.BLE.createGattClientDevice('8F:8F:8E:8E:6D:6D'); let ret = device.disconnect(); ``` ### close close(): boolean Closes this GATT client to unregister it from the protocol stack. After this method is called, this [GattClientDevice](#gattclientdevice) instance cannot be used. **Return values:** | Type | Description | | -------- | -------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise. | **Example:** ``` let device = bluetooth.BLE.createGattClientDevice('8F:8F:8E:8E:6D:6D'); let ret = device.close(); ``` ### getServices getServices(callback: AsyncCallback<Array<GattService>>): void Obtains all services of the peer BLE device. This method uses an asynchronous callback to return the result. **Parameters:** | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | | callback | AsyncCallback<Array<[GattService](#gattservice)>> | Yes | Callback invoked to return the services obtained. | **Return values:** None. **Example:** ``` // Callback function getServices(code, gattServices) { if (code.code == 0) { let services = gattServices; console.log('bluetooth code is ' + code.code); console.log("bluetooth services size is ", services.length); for (let i = 0; i < services.length; i++) { console.log('bluetooth serviceUuid is ' + services[i].serviceUuid); } } } let device = bluetooth.BLE.createGattClientDevice('8F:8F:8E:8E:6D:6D'); device.connect(); device.getServices(getServices); ``` ### getServices getServices(): Promise<Array<GattService>> Obtains all services of the peer BLE device. This method uses a promise to return the result. **Parameters:** **Return values:** | Type | Description | | -------- | -------- | | Promise<Array<[GattService](#gattservice)>> | Promise used to return the services obtained. | **Example:** ``` // Promise let device = bluetooth.BLE.createGattClientDevice('8F:8F:8E:8E:6D:6D'); device.connect(); let services = device.getServices(); console.log("bluetooth services size is ", services.length); for (let i = 0; i < services.length; i++) { console.log('bluetooth serviceUuid is ' + services[i].serviceUuid); } ``` ### readCharacteristicValue readCharacteristicValue(characteristic: BLECharacteristic, callback: AsyncCallback<BLECharacteristic>): void Reads the characteristic value of the specific service of the peer BLE device. This method uses an asynchronous callback to return the result. **Parameters:** | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | | characteristic | [BLECharacteristic](#blecharacteristic) | Yes | Characteristic value to read. | | callback | AsyncCallback<[BLECharacteristic](#blecharacteristic)> | Yes | Callback invoked to return the characteristic value read. | **Return values:** None. **Example:** ``` function readCcc(code, BLECharacteristic) { if (code.code != 0) { return; } console.log('bluetooth characteristic uuid: ' + BLECharacteristic.characteristicUuid); let value = new Uint8Array(BLECharacteristic.characteristicValue); console.log('bluetooth characteristic value: ' + value[0] +','+ value[1]+','+ value[2]+','+ value[3]); } let device = bluetooth.BLE.createGattClientDevice('8F:8F:8E:8E:6D:6D'); let descriptors = []; let bufferDesc = new ArrayBuffer(8); let descV = new Uint8Array(bufferDesc); descV[0] = 11; let descriptor = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', descriptorUuid: '00002903-0000-1000-8000-00805F9B34FB', descriptorValue: bufferDesc}; descriptors[0] = descriptor; let bufferCCC = new ArrayBuffer(8); let cccV = new Uint8Array(bufferCCC); cccV[0] = 1; let characteristic = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', characteristicValue: bufferCCC, descriptors:descriptors}; device.readCharacteristicValue(characteristic, readCcc); ``` ### readCharacteristicValue readCharacteristicValue(characteristic: BLECharacteristic): Promise<BLECharacteristic> Reads the characteristic value of the specific service of the peer BLE device. This method uses a promise to return the result. **Parameters:** | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | | characteristic | [BLECharacteristic](#blecharacteristic) | Yes | Characteristic value to read. | **Return values:** | Type | Description | | -------- | -------- | | Promise<[BLECharacteristic](#blecharacteristic)> | Promise used to return the characteristic value read. | **Example:** ``` let device = bluetooth.BLE.createGattClientDevice('8F:8F:8E:8E:6D:6D'); let descriptors = []; let bufferDesc = new ArrayBuffer(8); let descV = new Uint8Array(bufferDesc); descV[0] = 11; let descriptor = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', descriptorUuid: '00002903-0000-1000-8000-00805F9B34FB', descriptorValue: bufferDesc}; descriptors[0] = descriptor; let bufferCCC = new ArrayBuffer(8); let cccV = new Uint8Array(bufferCCC); cccV[0] = 1; let characteristic = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', characteristicValue: bufferCCC, descriptors:descriptors}; device.readCharacteristicValue(characteristic); ``` ### readDescriptorValue readDescriptorValue(descriptor: BLEDescriptor, callback: AsyncCallback<BLEDescriptor>): void Reads the descriptor contained in the specific characteristic of the peer BLE device. This method uses an asynchronous callback to return the result. **Parameters:** | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | | descriptor | [BLEDescriptor](#bledescriptor) | Yes | Descriptor to read. | | callback | AsyncCallback<[BLECharacteristic](#blecharacteristic)> | Yes | Callback invoked to return the descriptor read. | **Return values:** None. **Example:** ``` function readDesc(code, BLEDescriptor) { if (code.code != 0) { return; } console.log('bluetooth descriptor uuid: ' + BLEDescriptor.descriptorUuid); let value = new Uint8Array(BLEDescriptor.descriptorValue); console.log('bluetooth descriptor value: ' + value[0] +','+ value[1]+','+ value[2]+','+ value[3]); } let device = bluetooth.BLE.createGattClientDevice('8F:8F:8E:8E:6D:6D'); let bufferDesc = new ArrayBuffer(8); let descV = new Uint8Array(bufferDesc); descV[0] = 11; let descriptor = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', descriptorUuid: '00002903-0000-1000-8000-00805F9B34FB', descriptorValue: bufferDesc}; device.readDescriptorValue(descriptor, readDesc); ``` ### readDescriptorValue readDescriptorValue(descriptor: BLEDescriptor): Promise<BLEDescriptor> Reads the descriptor contained in the specific characteristic of the peer BLE device. This method uses a promise to return the result. **Parameters:** | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | | descriptor | [BLEDescriptor](#bledescriptor) | Yes | Descriptor to read. | **Return values:** | Type | Description | | -------- | -------- | | Promise<[BLEDescriptor](#bledescriptor)> | Promise used to return the descriptor read. | **Example:** ``` let device = bluetooth.BLE.createGattClientDevice('8F:8F:8E:8E:6D:6D'); let bufferDesc = new ArrayBuffer(8); let descV = new Uint8Array(bufferDesc); descV[0] = 11; let descriptor = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', descriptorUuid: '00002903-0000-1000-8000-00805F9B34FB', descriptorValue: bufferDesc}; device.readDescriptorValue(descriptor); ``` ### writeCharacteristicValue writeCharacteristicValue(characteristic: BLECharacteristic): boolean Writes a characteristic value to the peer BLE device. **Parameters:** | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | | characteristic | [BLECharacteristic](#blecharacteristic) | Yes | Binary value and other parameters of the BLE device characteristic. | **Return values:** | Name | Type | Mandatory | Description | | -------- | -------- | | Name | Type | Mandatory | Description | | boolean | Returns **true** if the operation is successful; returns **false** otherwise. | **Example:** ``` let device = bluetooth.BLE.createGattClientDevice('8F:8F:8E:8E:6D:6D'); let descriptors = []; let bufferDesc = new ArrayBuffer(8); let descV = new Uint8Array(bufferDesc); descV[0] = 11; let descriptor = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', descriptorUuid: '00002903-0000-1000-8000-00805F9B34FB', descriptorValue: bufferDesc}; descriptors[0] = descriptor; let bufferCCC = new ArrayBuffer(8); let cccV = new Uint8Array(bufferCCC); cccV[0] = 1; let characteristic = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', characteristicValue: bufferCCC, descriptors:descriptors}; let retWriteCcc = device.writeCharacteristicValue(characteristic); if (retWriteCcc) { console.log('write characteristic successfully'); } else { console.log('write characteristic failed'); } ``` ### writeDescriptorValue writeDescriptorValue(descriptor: BLEDescriptor): boolean Writes binary data to the specific descriptor of the peer BLE device. **Parameters:** | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | | descriptor | [BLEDescriptor](#bledescriptor) | Yes | Binary value and other parameters of the BLE device descriptor. | **Return values:** | Type | Description | | -------- | -------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise. | **Example:** ``` let device = bluetooth.BLE.createGattClientDevice('8F:8F:8E:8E:6D:6D'); let bufferDesc = new ArrayBuffer(8); let descV = new Uint8Array(bufferDesc); descV[0] = 22; let descriptor = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', descriptorUuid: '00002903-0000-1000-8000-00805F9B34FB', descriptorValue: bufferDesc}; let retWriteDesc = device.writeDescriptorValue(descriptor); if (retWriteDesc) { console.log('bluetooth write descriptor successfully'); } else { console.log('bluetooth write descriptor failed'); } ``` ### setBLEMtuSize setBLEMtuSize(mtu: number): boolean Sets the maximum transmission unit (MTU) that can be transmitted between the GATT client and its peer BLE device. This method can be used only after a connection is set up by calling **connect**. **Parameters:** | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | | mtu | number | Yes | MTU to set, which ranges from 22 to 512 bytes. | **Return values:** | Type | Description | | -------- | -------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise. | **Example:** ``` let device = bluetooth.BLE.createGattClientDevice('8F:8F:8E:8E:6D:6D'); device.setBLEMtuSize(128); ``` ### setNotifyCharacteristicChanged setNotifyCharacteristicChanged(characteristic: BLECharacteristic, enable: boolean): boolean Sets the function of notifying the GATT client when the characteristic value of the peer BLE device changes. **Parameters:** | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | | characteristic | [BLECharacteristic](#blecharacteristic) | Yes | BLE characteristic to listen for. | | enable | boolean | Yes | Whether to enable the notify function. The value **true** means to enable the notify function, and the value **false** means the opposite. | **Return values:** | Type | Description | | -------- | -------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise. | **Example:** ``` let device = bluetooth.BLE.createGattClientDevice('8F:8F:8E:8E:6D:6D'); device.setNotifyCharacteristicChanged(notifyCcc, false); ``` ### on('BLECharacteristicChange') on(type: "BLECharacteristicChange", callback: Callback<BLECharacteristic>): void Subscribes to the BLE characteristic change events. The client can receive a notification from the server only after the **setNotifyCharacteristicChanged** method is called. **Parameters:** | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | | type | string | Yes | Event type. The value **BLECharacteristicChange** indicates a characteristic value change event. | | callback | Callback<[BLECharacteristic](#blecharacteristic)> | Yes | Callback invoked to return the characteristic value changes. | **Return values:** None. **Example:** ``` function CharacteristicChange(CharacteristicChangeReq) { let serviceUuid = CharacteristicChangeReq.serviceUuid; let characteristicUuid = CharacteristicChangeReq.characteristicUuid; let value = new Uint8Array(CharacteristicChangeReq.characteristicValue); } let device = bluetooth.BLE.createGattClientDevice('8F:8F:8E:8E:6D:6D'); device.on('BLECharacteristicChange', CharacteristicChange); ``` ### off('BLECharacteristicChange') off(type: "BLECharacteristicChange", callback?: Callback<BLECharacteristic>): void Unsubscribes from the BLE characteristic change events. **Parameters:** | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | | type | string | Yes | Event type. The value **BLECharacteristicChange** indicates a characteristic value change event. | | callback | Callback<[BLECharacteristic](#blecharacteristic)> | No | Callback used to report the characteristic value. If this parameter is not set, this method unsubscribes from all callbacks corresponding to **type**. | **Return values:** None. **Example:** ``` let device = bluetooth.BLE.createGattClientDevice('8F:8F:8E:8E:6D:6D'); device.off('BLECharacteristicChange'); ``` ### on('BLEConnectionStateChange') on(type: "BLEConnectionStateChange", callback: Callback<BLEConnectChangedState>): void Subscribes to the BLE connection state change events. **Parameters:** | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | | type | string | Yes | Event type. The value **BLEConnectionStateChange** indicates a BLE connection state change event. | | callback | Callback<[BLEConnectChangedState](#bleconnectchangedstate)> | Yes | Callback invoked to return the BLE connection state. | **Return values:** None. **Example:** ``` function ConnectStateChanged(state) { console.log('bluetooth connect state changed'); let connectState = state.state; } let device = bluetooth.BLE.createGattClientDevice('8F:8F:8E:8E:6D:6D'); device.on('BLEConnectionStateChange', ConnectStateChanged); ``` ### off('BLEConnectionStateChange') off(type: "BLEConnectionStateChange", callback?: Callback<BLEConnectChangedState>): void Unsubscribes from the BLE connection state change events. **Parameters:** | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | | type | string | Yes | Event type. The value **BLEConnectionStateChange** indicates a BLE connection state change event. | | callback | Callback<[BLEConnectChangedState](#bleconnectchangedstate)> | No | Callback used to report the BLE connection state. If this parameter is not set, this method unsubscribes from all callbacks corresponding to **type**. | **Return values:** None. **Example:** ``` let device = bluetooth.BLE.createGattClientDevice('8F:8F:8E:8E:6D:6D'); device.off('BLEConnectionStateChange'); ``` ### getDeviceName getDeviceName(callback: AsyncCallback<string>): void Obtains the name of the peer BLE device. This method uses an asynchronous callback to return the result. **Parameters:** | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | | callback | AsyncCallback<string> | Yes | Callback invoked to return the peer BLE device name. | **Return values:** None. **Example:** ``` // Callback let gattClient = bluetooth.BLE.createGattClientDevice("8F:8F:8E:8E:6D:6D"); let deviceName = gattClient.getDeviceName((err, data)=> { console.info('device name err ' + JSON.stringify(err)); console.info('device name' + JSON.stringify(data)); }) ``` ### getDeviceName getDeviceName(): Promise<string> Obtains the name of the peer BLE device. This method uses a promise to return the result. **Return values:** | Type | Description | | -------- | -------- | | Promise<string> | Promise used to return the peer BLE device name. | **Example:** ``` // Promise let gattClient = bluetooth.BLE.createGattClientDevice("8F:8F:8E:8E:6D:6D"); let ret = device.connect(); let deviceName = gattClient.getDeviceName().then((data) => { console.info('device name' + JSON.stringify(data)); }) ``` ### getRssiValue getRssiValue(callback: AsyncCallback<number>): void Obtains the received signal strength indication (RSSI) of the peer BLE device. This method uses an asynchronous callback to return the result. It can be used only after a connection is set up by calling [connect](#connect-boolean). **Parameters:** | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | | callback | AsyncCallback<number> | Yes | Callback invoked to return the RSSI, in dBm. | **Return values:** None. **Example:** ``` // Callback let gattClient = bluetooth.BLE.createGattClientDevice("8F:8F:8E:8E:6D:6D"); let ret = device.connect(); let rssi = gattClient.getRssiValue((err, data)=> { console.info('rssi err ' + JSON.stringify(err)); console.info('rssi value' + JSON.stringify(data)); }) ``` ### getRssiValue getRssiValue(): Promise<number> Obtains the RSSI of the peer BLE device. This method uses a promise to return the result. It can be used only after a connection is set up by calling [connect](#connect-boolean). **Return values:** | Type | Description | | -------- | -------- | | Promise<number> | Promise used to return the RSSI, in dBm. | **Example:** ``` // Promise let gattClient = bluetooth.BLE.createGattClientDevice("8F:8F:8E:8E:6D:6D"); let rssi = gattClient.getRssiValue().then((data) => { console.info('rssi' + JSON.stringify(data)); }) ``` ## ScanMode Enumerates the scan modes. | Mode | Default Value | Description | | -------- | -------- | -------- | | SCAN_MODE_NONE | 0 | No scan mode is specified. | | SCAN_MODE_CONNECTABLE | 1 | Discoverable mode. | | SCAN_MODE_GENERAL_DISCOVERABLE | 2 | General discoverable mode. | | SCAN_MODE_LIMITED_DISCOVERABLE | 3 | Limited discoverable mode. | | SCAN_MODE_CONNECTABLE_GENERAL_DISCOVERABLE | 4 | General connectable and discoverable mode. | | SCAN_MODE_CONNECTABLE_LIMITED_DISCOVERABLE | 5 | Limited connectable and discoverable mode. | ## BondState Enumerates the pairing states. | State | Default Value | Description | | -------- | -------- | -------- | | BOND_STATE_INVALID | 0 | Invalid pairing. | | BOND_STATE_BONDING | 1 | Pairing. | | BOND_STATE_BONDED | 2 | Paired. | ## SppOption Defines the SPP configuration parameters. | Name | Type | Readable | Writable | Description | | -------- | -------- | -------- | -------- | -------- | | uuid | string | Yes | Yes | UUID of the SPP. | | isPrimary | boolean | Yes | Yes | Whether it is a secure channel. | | type | [SppType](#SppType) | Yes | Yes | Type of the SPP link. | ## SppType Enumerates the SPP link types. | Type | Default Value | Description | | -------- | -------- | -------- | | SPP_RFCOMM | 0 | Radio frequency communication (RFCOMM) link type. | ## GattService Defines the GATT service API parameters. | Name | Type | Readable | Writable | Description | | -------- | -------- | -------- | -------- | -------- | | serviceUuid | string | Yes | Yes | UUID of the service, for example, **00001888-0000-1000-8000-00805f9b34fb**. | | isPrimary | boolean | Yes | Yes | Whether the service is a primary service. The value **true** means a primary service. | | characteristics | Array<[BLECharacteristic](#BLECharacteristic)> | Yes | Yes | List of characteristics of the service. | | includeServices | Array<[GattService](#GattService)> | Yes | Yes | Services on which the service depends. | ## BLECharacteristic Defines the characteristic API parameters. | Name | Type | Readable | Writable | Description | | -------- | -------- | -------- | -------- | -------- | | serviceUuid | string | Yes | Yes | UUID of the service, for example, **00001888-0000-1000-8000-00805f9b34fb**. | | characteristicUuid | string | Yes | Yes | UUID of the characteristic, for example, **00002a11-0000-1000-8000-00805f9b34fb**. | | characteristicValue | ArrayBuffer | Yes | Yes | Binary value of the characteristic. | | descriptors | Array<[BLEDescriptor](#BLEDescriptor)> | Yes | Yes | List of descriptors of the characteristic. | ## BLEDescriptor Defines the descriptor API parameters. | Name | Type | Readable | Writable | Description | | -------- | -------- | -------- | -------- | -------- | | serviceUuid | string | Yes | Yes | UUID of the service, for example, **00001888-0000-1000-8000-00805f9b34fb**. | | characteristicUuid | string | Yes | Yes | UUID of the characteristic, for example, **00002a11-0000-1000-8000-00805f9b34fb**. | | descriptorUuid | string | Yes | Yes | UUID of the descriptor, for example, **00002902-0000-1000-8000-00805f9b34fb**. | | descriptorValue | ArrayBuffer | Yes | Yes | Binary value of the descriptor. | ## NotifyCharacteristic Defines the parameters in the notifications sent when the server characteristic value changes. | Name | Type | Readable | Writable | Description | | -------- | -------- | -------- | -------- | -------- | | serviceUuid | string | Yes | Yes | UUID of the service, for example, **00001888-0000-1000-8000-00805f9b34fb**. | | characteristicUuid | string | Yes | Yes | UUID of the characteristic, for example, **00002a11-0000-1000-8000-00805f9b34fb**. | | characteristicValue | ArrayBuffer | Yes | Yes | Binary value of the characteristic. | | confirm | boolean | Yes | Yes | Whether the notification needs to be confirmed by the peer end. For a notification, set it to **true**. In this case, the peer end must confirm the receipt of the notification. For an indication, set it to **false**. In this case, the peer end does not need to confirm the receipt of the notification. | ## CharacteristicReadReq Defines the parameters of the **CharacteristicReadReq** event received by the server. | Name | Type | Readable | Writable | Description | | -------- | -------- | -------- | -------- | -------- | | deviceId | string | Yes | No | Address of the client that sends the request, for example, **8F:8F:8E:8E:6D:6D**. | | transId | number | Yes | No | Transmission ID of the read request. The response returned by the server must use the same transmission ID. | | offset | number | Yes | No | Position from which the characteristic value is read. For example, **k** means to read from the _k_th byte. The response returned by the server must use the same offset. | | characteristicUuid | string | Yes | No | UUID of the characteristic, for example, **00002a11-0000-1000-8000-00805f9b34fb**. | | serviceUuid | string | Yes | No | UUID of the service, for example, **00001888-0000-1000-8000-00805f9b34fb**. | ## CharacteristicWriteReq Defines the parameters of the **CharacteristicWriteReq** event received by the server. | Name | Type | Readable | Writable | Description | | -------- | -------- | -------- | -------- | -------- | | deviceId | string | Yes | No | Address of the client that sends the request, for example, **8F:8F:8E:8E:6D:6D**. | | transId | number | Yes | No | Transmission ID of the write request. The response returned by the server must use the same transmission ID. | | offset | number | Yes | No | Start position for writing the characteristic value. For example, **k** means to write from the _k_th byte. The response returned by the server must use the same offset. | | descriptorUuid | string | Yes | No | UUID of the descriptor, for example, **00002902-0000-1000-8000-00805f9b34fb**. | | characteristicUuid | string | Yes | No | UUID of the characteristic, for example, **00002a11-0000-1000-8000-00805f9b34fb**. | | serviceUuid | string | Yes | No | UUID of the service, for example, **00001888-0000-1000-8000-00805f9b34fb**. | ## DescriptorReadReq Defines the parameters of the **DescriptorReadReq** event received by the server. | Name | Type | Readable | Writable | Description | | -------- | -------- | -------- | -------- | -------- | | deviceId | string | Yes | No | Address of the client that sends the request, for example, **8F:8F:8E:8E:6D:6D**. | | transId | number | Yes | No | Transmission ID of the read request. The response returned by the server must use the same transmission ID. | | offset | number | Yes | No | Position from which the descriptor is read. For example, **k** means to read from the _k_th byte. The response returned by the server must use the same offset. | | descriptorUuid | string | Yes | No | UUID of the descriptor, for example, **00002902-0000-1000-8000-00805f9b34fb**. | | characteristicUuid | string | Yes | No | UUID of the characteristic, for example, **00002a11-0000-1000-8000-00805f9b34fb**. | | serviceUuid | string | Yes | No | UUID of the service, for example, **00001888-0000-1000-8000-00805f9b34fb**. | ## DescriptorWriteReq Defines the parameters of the **DescriptorWriteReq** event received by the server. | Name | Type | Readable | Writable | Description | | -------- | -------- | -------- | -------- | -------- | | deviceId | string | Yes | No | Address of the client that sends the request, for example, **8F:8F:8E:8E:6D:6D**. | | transId | number | Yes | No | Transmission ID of the write request. The response returned by the server must use the same transmission ID. | | offset | number | Yes | No | Start position for writing the descriptor. For example, **k** means to write from the _k_th byte. The response returned by the server must use the same offset. | | isPrep | boolean | Yes | No | Whether the write request is executed immediately. | | needRsp | boolean | Yes | No | Whether to send a response to the GATT client. | | value | ArrayBuffer | Yes | No | Binary value of the descriptor to write. | | descriptorUuid | string | Yes | No | UUID of the descriptor, for example, **00002902-0000-1000-8000-00805f9b34fb**. | | characteristicUuid | string | Yes | No | UUID of the characteristic, for example, **00002a11-0000-1000-8000-00805f9b34fb**. | | serviceUuid | string | Yes | No | UUID of the service, for example, **00001888-0000-1000-8000-00805f9b34fb**. | ## ServerResponse Defines the parameters of the server's response to the GATT client's read/write request. | Name | Type | Readable | Writable | Description | | -------- | -------- | -------- | -------- | -------- | | deviceId | string | Yes | No | Address of the client, for example, **8F:8F:8E:8E:6D:6D**. | | 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. | | status | number | Yes | No | Response state. Set this parameter to **0**, which indicates a normal response. | | offset | number | Yes | No | Start read/write position. The value must be the same as the **offset** carried in the read/write request. | | value | ArrayBuffer | Yes | No | Binary data in the response. | ## BLEConnectChangedState Defines the parameters of **BLEConnectChangedState**. | Name | Type | Readable | Writable | Description | | -------- | -------- | -------- | -------- | -------- | | deviceId | string | Yes | No | Address of the peer device, for example, **8F:8F:8E:8E:6D:6D**. | | state | [ProfileConnectionState](#ProfileConnectionState) | Yes | Yes | BLE connection state. | ## ProfileConnectionState Enumerates the profile connection states. | Name | Default Value | Description | | -------- | -------- | -------- | | STATE_DISCONNECTED | 0 | Disconnected. | | STATE_CONNECTING | 1 | Connecting. | | STATE_CONNECTED | 2 | Connected. | | STATE_DISCONNECTING | 3 | Disconnecting. | ## ScanFilter Defines the scan filter parameters. | Name | Type | Readable | Writable | Description | | -------- | -------- | -------- | -------- | -------- | | deviceId | string | Yes | Yes | Address of the BLE device to filter, for example, **8F:8F:8E:8E:6D:6D**. | | name | string | Yes | Yes | Name of the BLE device to filter. | | serviceUuid | string | Yes | Yes | UUID of the service, for example, **00001888-0000-1000-8000-00805f9b34fb**. | ## ScanOptions Defines the scan configuration parameters. | Name | Type | Readable | Writable | Description | | -------- | -------- | -------- | -------- | -------- | | interval | number | Yes | Yes | Delay in reporting the scan result. The default value is **0**. | | dutyMode | [ScanDuty](#ScanDuty) | Yes | Yes | Scan duty. The default value is **SCAN_MODE_LOW_POWER**. | | matchMode | [MatchMode](#MatchMode) | Yes | Yes | Hardware match mode for BLE scan filters. The default value is **MATCH_MODE_AGGRESSIVE**. | ## ScanDuty Enumerates the scan duty options. | Name | Default Value | Description | | -------- | -------- | -------- | | SCAN_MODE_LOW_POWER | 0 | Low-power mode, which is the default value. | | SCAN_MODE_BALANCED | 1 | Balanced mode. | | SCAN_MODE_LOW_LATENCY | 2 | Low-latency mode. | ## MatchMode Enumerates the hardware match modes of BLE scan filters. | Name | Default Value | Description | | -------- | -------- | -------- | | 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. | | SCAN_MODE_LOW_LATENCY | 2 | Hardware reports the scan result with a higher threshold of signal strength and sightings. | ## ScanResult Defines the scan result. | Name | Type | Readable | Writable | Description | | -------- | -------- | -------- | -------- | -------- | | deviceId | string | Yes | No | Address of the device discovered, for example, **8F:8F:8E:8E:6D:6D**. | | rssi | number | Yes | No | RSSI of the device. | | data | ArrayBuffer | Yes | No | Advertisement packets sent by the device. | ## BluetoothState Enumerates the Bluetooth states. | Name | Default Value | Description | | -------- | -------- | -------- | | STATE_OFF | 0 | Bluetooth is turned off. | | STATE_TURNING_ON | 1 | Bluetooth is being turned on. | | STATE_ON | 2 | Bluetooth is turned on. | | STATE_TURNING_OFF | 3 | Bluetooth is being turned off. | | STATE_BLE_TURNING_ON | 4 | The LE-only mode is being turned on for Bluetooth. | | STATE_BLE_ON | 5 | Bluetooth is in LE-only mode. | | STATE_BLE_TURNING_OFF | 6 | The LE-only mode is being turned off for Bluetooth. | ## AdvertiseSetting Defines the BLE advertising parameters. | Name | Type | Readable | Writable | Description | | -------- | -------- | -------- | -------- | -------- | | interval | number | Yes | Yes | Interval for BLE advertising. The minimum value is **32** slots (20 ms). The maximum value is **16777215** slots. The default value is **1600** slots (1s). | | txPower | number | Yes | Yes | Transmit power, in dBm. The value range is –127 to 1. The default value is **–7**. | | connectable | boolean | Yes | Yes | Whether the advertisement is connectable. The default value is **true**. | ## AdvertiseData Defines the content of a BLE advertisement packet. | Name | Type | Readable | Writable | Description | | -------- | -------- | -------- | -------- | -------- | | serviceUuids | Array<string> | Yes | Yes | List of service UUIDs to be broadcasted. | | manufactureData | Array<[ManufactureData](#ManufactureData)> | Yes | Yes | List of manufacturers to be broadcasted. | | serviceData | Array<[ServiceData](#ServiceData)> | Yes | Yes | List of service data to be broadcasted. | ## ManufactureData Defines the content of a BLE advertisement packet. | Name | Type | Readable | Writable | Description | | -------- | -------- | -------- | -------- | -------- | | manufactureId | Array<string> | Yes | Yes | Manufacturer ID allocated by the Bluetooth SIG. | | manufactureValue | ArrayBuffer | Yes | Yes | Manufacturer data. | ## ServiceData Defines the service data contained in an advertisement packet. | Name | Type | Readable | Writable | Description | | -------- | -------- | -------- | -------- | -------- | | serviceUuid | string | Yes | Yes | Service UUID. | | serviceValue | ArrayBuffer | Yes | Yes | Service data. | ## PinRequiredParam Defines the pairing request parameters. | Name | Type | Readable | Writable | Description | | -------- | -------- | -------- | -------- | -------- | | deviceId | string | Yes | No | ID of the device to pair. | | pinCode | string | Yes | No | Key for the device pairing. |