harmony 鸿蒙@ohos.bluetooth.ble (Bluetooth BLE Module)

2023-10-30 浏览 (1371)

@ohos.bluetooth.ble (Bluetooth BLE Module)

The ble module provides APIs for operating and managing Bluetooth.

NOTE

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.

Modules to Import

import ble from '@ohos.bluetooth.ble';

ble.createGattServer

createGattServer(): GattServer

Creates a GattServer instance.

System capability: SystemCapability.Communication.Bluetooth.Core

Return value

TypeDescription
GattServerGattServer instance created.

Example

let gattServer: ble.GattServer = ble.createGattServer();
console.info('gatt success');

ble.createGattClientDevice

createGattClientDevice(deviceId: string): GattClientDevice

Creates a GattClientDevice instance.

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
deviceIdstringYesAddress of the remote device, for example, XX:XX:XX:XX:XX:XX.

Return value

TypeDescription
GattClientDeviceGattClientDevice instance created. Before using an API of the client, you must create a GattClientDevice instance.

Example

import { BusinessError } from '@ohos.base';
try {
    let device: ble.GattClientDevice = ble.createGattClientDevice('XX:XX:XX:XX:XX:XX');
} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

ble.getConnectedBLEDevices

getConnectedBLEDevices(): Array<string>

Obtains the Bluetooth Low Energy (BLE) devices connected to this device.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Return value

TypeDescription
Array<string>Addresses of the BLE devices connected to this device.

Error codes

For details about the error codes, see Bluetooth Error Codes.

IDError Message
2900001Service stopped.
2900003Bluetooth switch is off.
2900099Operation failed.

Example

import { BusinessError } from '@ohos.base';
try {
    let result: Array<string> = ble.getConnectedBLEDevices();
} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

ble.startBLEScan

startBLEScan(filters: Array<ScanFilter>, options?: ScanOptions): void

Starts a BLE scan.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
filtersArray<ScanFilter>YesCriteria for filtering the scan result. Set this parameter to null if you do not want to filter the scan result.
optionsScanOptionsNoScan options.

Error codes

For details about the error codes, see Bluetooth Error Codes.

IDError Message
2900001Service stopped.
2900003Bluetooth switch is off.
2900099Operation failed.

Example

import { BusinessError } from '@ohos.base';
function onReceiveEvent(data: Array<ble.ScanResult>) {
    console.info('BLE scan device find result = '+ JSON.stringify(data));
}
try {
    ble.on("BLEDeviceFind", onReceiveEvent);
    let scanFilter: ble.ScanFilter = {
            deviceId:"XX:XX:XX:XX:XX:XX",
            name:"test",
            serviceUuid:"00001888-0000-1000-8000-00805f9b34fb"
        };
    let scanOptions: ble.ScanOptions = {
    interval: 500,
    dutyMode: ble.ScanDuty.SCAN_MODE_LOW_POWER,
    matchMode: ble.MatchMode.MATCH_MODE_AGGRESSIVE,
    }
    ble.startBLEScan([scanFilter],scanOptions);
} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

ble.stopBLEScan

stopBLEScan(): void

Stops the BLE scan.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Error codes

For details about the error codes, see Bluetooth Error Codes.

IDError Message
2900001Service stopped.
2900003Bluetooth switch is off.
2900099Operation failed.

Example

import { BusinessError } from '@ohos.base';
try {
    ble.stopBLEScan();
} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

ble.startAdvertising

startAdvertising(setting: AdvertiseSetting, advData: AdvertiseData, advResponse?: AdvertiseData): void

Starts BLE advertising.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
settingAdvertiseSettingYesSettings related to BLE advertising.
advDataAdvertiseDataYesContent of the BLE advertisement packet.
advResponseAdvertiseDataNoResponse to the BLE scan request.

Error codes

For details about the error codes, see Bluetooth Error Codes.

IDError Message
2900001Service stopped.
2900003Bluetooth switch is off.
2900099Operation failed.

Example

import { BusinessError } from '@ohos.base';
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));
try {
    let setting: ble.AdvertiseSetting = {
        interval:150,
        txPower:0,
        connectable:true,
    };
    let manufactureDataUnit: ble.ManufactureData = {
        manufactureId:4567,
        manufactureValue:manufactureValueBuffer.buffer
    };
    let serviceDataUnit: ble.ServiceData = {
        serviceUuid:"00001888-0000-1000-8000-00805f9b34fb",
        serviceValue:serviceValueBuffer.buffer
    };
    let advData: ble.AdvertiseData = {
        serviceUuids:["00001888-0000-1000-8000-00805f9b34fb"],
        manufactureData:[manufactureDataUnit],
        serviceData:[serviceDataUnit],
    };
    let advResponse: ble.AdvertiseData = {
        serviceUuids:["00001888-0000-1000-8000-00805f9b34fb"],
        manufactureData:[manufactureDataUnit],
        serviceData:[serviceDataUnit],
    };
    ble.startAdvertising(setting, advData ,advResponse);
} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

ble.stopAdvertising

stopAdvertising(): void

Stops BLE advertising.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Error codes

For details about the error codes, see Bluetooth Error Codes.

IDError Message
2900001Service stopped.
2900003Bluetooth switch is off.
2900099Operation failed.

Example

import { BusinessError } from '@ohos.base';
try {
    ble.stopAdvertising();
} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

ble.on('BLEDeviceFind')

on(type: 'BLEDeviceFind', callback: Callback<Array<ScanResult>>): void

Subscribes to BLE device discovery events.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value is BLEDeviceFind, which indicates an event of discovering a BLE device.
callbackCallback<Array<ScanResult>>YesCallback invoked to return the discovered devices. You need to implement this callback.

Error codes

For details about the error codes, see Bluetooth Error Codes.

IDError Message
2900099Operation failed.

Example

import { BusinessError } from '@ohos.base';
function onReceiveEvent(data: Array<ble.ScanResult>) {
    console.info('bluetooth device find = '+ JSON.stringify(data));
}
try {
    ble.on('BLEDeviceFind', onReceiveEvent);
} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

ble.off('BLEDeviceFind')

off(type: 'BLEDeviceFind', callback?: Callback<Array<ScanResult>>): void

Unsubscribes from the BLE device discovery events.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value is BLEDeviceFind, which indicates an event of discovering a BLE device.
callbackCallback<Array<ScanResult>>NoCallback for the BLEDeviceFind event. If this parameter is not set, this API unsubscribes from all callbacks corresponding to type.

Error codes

For details about the error codes, see Bluetooth Error Codes.

IDError Message
2900099Operation failed.

Example

import { BusinessError } from '@ohos.base';
function onReceiveEvent(data: Array<ble.ScanResult>) {
    console.info('bluetooth device find = '+ JSON.stringify(data));
}
try {
    ble.on('BLEDeviceFind', onReceiveEvent);
    ble.off('BLEDeviceFind', onReceiveEvent);
} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

GattServer

Implements the Generic Attribute Profile (GATT) server. Before using an API of this class, you need to create a GattServer instance using createGattServer().

addService

addService(service: GattService): void

Adds a service to this GATT server.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
serviceGattServiceYesService to add. Settings related to BLE advertising.

Error codes

For details about the error codes, see Bluetooth Error Codes.

IDError Message
2900001Service stopped.
2900003Bluetooth switch is off.
2900099Operation failed.

Example

import { BusinessError } from '@ohos.base';
// Create descriptors.
let descriptors: Array<ble.BLEDescriptor> = [];
let arrayBuffer = new ArrayBuffer(8);
let descV = new Uint8Array(arrayBuffer);
descV[0] = 11;
let descriptor: ble.BLEDescriptor = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB',
  characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB',
  descriptorUuid: '00002902-0000-1000-8000-00805F9B34FB', descriptorValue: arrayBuffer};
descriptors[0] = descriptor;

// Create characteristics.
let characteristics: Array<ble.BLECharacteristic> = [];
let arrayBufferC = new ArrayBuffer(8);
let cccV = new Uint8Array(arrayBufferC);
cccV[0] = 1;
let characteristic: ble.BLECharacteristic = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB',
  characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', characteristicValue: arrayBufferC, descriptors:descriptors};
let characteristicN: ble.BLECharacteristic = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB',
  characteristicUuid: '00001821-0000-1000-8000-00805F9B34FB', characteristicValue: arrayBufferC, descriptors:descriptors};
characteristics[0] = characteristic;

// Create a gattService instance.
let gattService: ble.GattService = {serviceUuid:'00001810-0000-1000-8000-00805F9B34FB', isPrimary: true, characteristics:characteristics, includeServices:[]};

try {
    let gattServer: ble.GattServer = ble.createGattServer(); 
    gattServer.addService(gattService);
} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

removeService

removeService(serviceUuid: string): void

Removes a service from this GATT server.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
serviceUuidstringYesUniversally unique identifier (UUID) of the service to remove, for example, 00001810-0000-1000-8000-00805F9B34FB.

Error codes

For details about the error codes, see Bluetooth Error Codes.

IDError Message
2900001Service stopped.
2900003Bluetooth switch is off.
2900004Profile is not supported.
2900099Operation failed.

Example

import { BusinessError } from '@ohos.base';
let server: ble.GattServer = ble.createGattServer();
try {
    server.removeService('00001810-0000-1000-8000-00805F9B34FB');
} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

close

close(): void

Closes this GATT server to unregister it from the protocol stack. The closed GattServer instance will no longer be used.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Error codes

For details about the error codes, see Bluetooth Error Codes.

IDError Message
2900001Service stopped.
2900003Bluetooth switch is off.
2900099Operation failed.

Example

import { BusinessError } from '@ohos.base';
let server: ble.GattServer = ble.createGattServer();
try {
    server.close();
} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

notifyCharacteristicChanged

notifyCharacteristicChanged(deviceId: string, notifyCharacteristic: NotifyCharacteristic, callback: AsyncCallback<void>): void

Notifies a connected client device when a characteristic value changes. This API uses an asynchronous callback to return the result.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
deviceIdstringYesAddress of the client that receives the notifications, for example, XX:XX:XX:XX:XX:XX.
notifyCharacteristicNotifyCharacteristicYesNew characteristic value.
callbackAsyncCallback<void>YesCallback invoked to return the result. If the operation is successful, err is undefined; otherwise, err is an error object.

Error codes

For details about the error codes, see Bluetooth Error Codes.

IDError Message
2900001Service stopped.
2900003Bluetooth switch is off.
2900099Operation failed.

Example

import { BusinessError } from '@ohos.base';
let arrayBufferC = new ArrayBuffer(8);
let notifyCharacter: ble.NotifyCharacteristic = {
    serviceUuid: '00001810-0000-1000-8000-00805F9B34FB',
    characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB',
    characteristicValue: arrayBufferC,
    confirm: true,
};
try {
    let gattServer: ble.GattServer = ble.createGattServer();
    gattServer.notifyCharacteristicChanged('XX:XX:XX:XX:XX:XX', notifyCharacter, (err: BusinessError) => {
        if (err) {
            console.info('notifyCharacteristicChanged callback failed');
        } else {
            console.info('notifyCharacteristicChanged callback successful');
        }
    });
} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

notifyCharacteristicChanged

notifyCharacteristicChanged(deviceId: string, notifyCharacteristic: NotifyCharacteristic): Promise<void>

Notifies a connected client device when a characteristic value changes. This API uses a promise to return the result.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
deviceIdstringYesAddress of the client that receives the notifications, for example, XX:XX:XX:XX:XX:XX.
notifyCharacteristicNotifyCharacteristicYesNew characteristic value.

Return value

TypeDescription
Promise<void>Promise used to return the result.

Error codes

For details about the error codes, see Bluetooth Error Codes.

IDError Message
2900001Service stopped.
2900003Bluetooth switch is off.
2900099Operation failed.

Example

import { BusinessError } from '@ohos.base';
let arrayBufferC = new ArrayBuffer(8);
let notifyCharacter: ble.NotifyCharacteristic = {
    serviceUuid: '00001810-0000-1000-8000-00805F9B34FB',
    characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB',
    characteristicValue: arrayBufferC,
    confirm: true,
};
try {
    let gattServer: ble.GattServer = ble.createGattServer();
    gattServer.notifyCharacteristicChanged('XX:XX:XX:XX:XX:XX', notifyCharacter).then(() => {
        console.info('notifyCharacteristicChanged promise successfull');
    });
} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

sendResponse

sendResponse(serverResponse: ServerResponse): void

Sends a response to a read or write request from the GATT client.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
serverResponseServerResponseYesResponse returned by the GATT server.

Error codes

For details about the error codes, see Bluetooth Error Codes.

IDError Message
2900001Service stopped.
2900003Bluetooth switch is off.
2900099Operation failed.

Example

import { BusinessError } from '@ohos.base';
/* send response */
let arrayBufferCCC = new ArrayBuffer(8);
let cccValue = new Uint8Array(arrayBufferCCC);
cccValue[0] = 1123;
let serverResponse: ble.ServerResponse = {
    deviceId: 'XX:XX:XX:XX:XX:XX',
    transId: 0,
    status: 0,
    offset: 0,
    value: arrayBufferCCC,
};
try {
    let gattServer: ble.GattServer = ble.createGattServer();
    gattServer.sendResponse(serverResponse);
} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

on('characteristicRead')

on(type: 'characteristicRead', callback: Callback<CharacteristicReadRequest>): void

Subscribes to characteristic read request events.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value is characteristicRead, which indicates a characteristic read request event.
callbackCallback<CharacteristicReadRequest>YesCallback invoked to return a characteristic read request event from the GATT client.

Example

import { BusinessError } from '@ohos.base';
let arrayBufferCCC = new ArrayBuffer(8);
let cccValue = new Uint8Array(arrayBufferCCC);
cccValue[0] = 1123;
let gattServer: ble.GattServer = ble.createGattServer();
function ReadCharacteristicReq(characteristicReadRequest: ble.CharacteristicReadRequest) {
    let deviceId: string = characteristicReadRequest.deviceId;
    let transId: number = characteristicReadRequest.transId;
    let offset: number = characteristicReadRequest.offset;
    let characteristicUuid: string = characteristicReadRequest.characteristicUuid;

    let serverResponse: ble.ServerResponse = {deviceId: deviceId, transId: transId, status: 0, offset: offset, value:arrayBufferCCC};

    try {
        gattServer.sendResponse(serverResponse);
    } catch (err) {
        console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
    }
}
gattServer.on('characteristicRead', ReadCharacteristicReq);

off('characteristicRead')

off(type: 'characteristicRead', callback?: Callback<CharacteristicReadRequest>): void

Unsubscribes from characteristic read request events.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value is characteristicRead, which indicates a characteristic read request event.
callbackCallback<CharacteristicReadRequest>NoCallback for the characteristic read request event. If this parameter is not set, this API unsubscribes from all callbacks corresponding to type.

Example

import { BusinessError } from '@ohos.base';
try {
let gattServer: ble.GattServer = ble.createGattServer();
gattServer.off('characteristicRead');
} catch (err) {
    console.error("errCode:" + (err as BusinessError).code + ",errMessage:" + (err as BusinessError).message);
}

on('characteristicWrite')

on(type: 'characteristicWrite', callback: Callback<CharacteristicWriteRequest>): void

Subscribes to characteristic write request events.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value is characteristicWrite, which indicates a characteristic write request event.
callbackCallback<CharacteristicWriteRequest>YesCallback invoked to return a characteristic write request from the GATT client.

Example

import { BusinessError } from '@ohos.base';
let arrayBufferCCC = new ArrayBuffer(8);
let cccValue = new Uint8Array(arrayBufferCCC);
let gattServer: ble.GattServer = ble.createGattServer();
function WriteCharacteristicReq(characteristicWriteRequest: ble.CharacteristicWriteRequest) {
    let deviceId: string = characteristicWriteRequest.deviceId;
    let transId: number = characteristicWriteRequest.transId;
    let offset: number = characteristicWriteRequest.offset;
    let isPrepared: boolean = characteristicWriteRequest.isPrepared;
    let needRsp: boolean = characteristicWriteRequest.needRsp;
    let value: Uint8Array =  new Uint8Array(characteristicWriteRequest.value);
    let characteristicUuid: string = characteristicWriteRequest.characteristicUuid;

    cccValue[0] = value[0];
    let serverResponse: ble.ServerResponse = {deviceId: deviceId, transId: transId, status: 0, offset: offset, value:arrayBufferCCC};

    try {
        gattServer.sendResponse(serverResponse);
    } catch (err) {
        console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
    }
}
gattServer.on('characteristicWrite', WriteCharacteristicReq);

off('characteristicWrite')

off(type: 'characteristicWrite', callback?: Callback<CharacteristicWriteRequest>): void

Unsubscribes from characteristic write request events.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value is characteristicWrite, which indicates a characteristic write request event.
callbackCallback<CharacteristicWriteRequest>NoCallback for the characteristic write request event. If this parameter is not set, this API unsubscribes from all callbacks corresponding to type.

Example

import { BusinessError } from '@ohos.base';
try {
let gattServer: ble.GattServer = ble.createGattServer();
gattServer.off('characteristicWrite');
} catch (err) {
    console.error("errCode:" + (err as BusinessError).code + ",errMessage:" + (err as BusinessError).message);
}

on('descriptorRead')

on(type: 'descriptorRead', callback: Callback<DescriptorReadRequest>): void

Subscribes to descriptor read request events.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value is descriptorRead, which indicates a descriptor read request event.
callbackCallback<DescriptorReadRequest>YesCallback invoked to return a descriptor read request event from the GATT client.

Example

import { BusinessError } from '@ohos.base';
let arrayBufferDesc = new ArrayBuffer(8);
let descValue = new Uint8Array(arrayBufferDesc);
descValue[0] = 1101;
let gattServer: ble.GattServer = ble.createGattServer();
function ReadDescriptorReq(descriptorReadRequest: ble.DescriptorReadRequest) {
    let deviceId: string = descriptorReadRequest.deviceId;
    let transId: number = descriptorReadRequest.transId;
    let offset: number = descriptorReadRequest.offset;
    let descriptorUuid: string = descriptorReadRequest.descriptorUuid;

    let serverResponse: ble.ServerResponse = {deviceId: deviceId, transId: transId, status: 0, offset: offset, value:arrayBufferDesc};

    try {
        gattServer.sendResponse(serverResponse);
    } catch (err) {
        console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
    }
}
gattServer.on('descriptorRead', ReadDescriptorReq);

off('descriptorRead')

off(type: 'descriptorRead', callback?: Callback<DescriptorReadRequest>): void

Unsubscribes from descriptor read request events.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value is descriptorRead, which indicates a descriptor read request event.
callbackCallback<DescriptorReadRequest>NoCallback for the descriptor read request event. If this parameter is not set, this API unsubscribes from all callbacks corresponding to type.

Example

import { BusinessError } from '@ohos.base';
try {
let gattServer: ble.GattServer = ble.createGattServer();
gattServer.off('descriptorRead');
} catch (err) {
    console.error("errCode:" + (err as BusinessError).code + ",errMessage:" + (err as BusinessError).message);
}

on('descriptorWrite')

on(type: 'descriptorWrite', callback: Callback<DescriptorWriteRequest>): void

Subscribes to descriptor write request events.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value is descriptorWrite, which indicates a descriptor write request event.
callbackCallback<DescriptorWriteRequest>YesCallback invoked to return a descriptor write request from the GATT client.

Example

import { BusinessError } from '@ohos.base';
let arrayBufferDesc = new ArrayBuffer(8);
let descValue = new Uint8Array(arrayBufferDesc);
let gattServer: ble.GattServer = ble.createGattServer();
function WriteDescriptorReq(descriptorWriteRequest: ble.DescriptorWriteRequest) {
    let deviceId: string = descriptorWriteRequest.deviceId;
    let transId: number = descriptorWriteRequest.transId;
    let offset: number = descriptorWriteRequest.offset;
    let isPrepared: boolean = descriptorWriteRequest.isPrepared;
    let needRsp: boolean = descriptorWriteRequest.needRsp;
    let value: Uint8Array = new Uint8Array(descriptorWriteRequest.value);
    let descriptorUuid: string = descriptorWriteRequest.descriptorUuid;

    descValue[0] = value[0];
    let serverResponse: ble.ServerResponse = {deviceId: deviceId, transId: transId, status: 0, offset: offset, value:arrayBufferDesc};

    try {
        gattServer.sendResponse(serverResponse);
    } catch (err) {
        console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
    }
}
gattServer.on('descriptorWrite', WriteDescriptorReq);

off('descriptorWrite')

off(type: 'descriptorWrite', callback?: Callback<DescriptorWriteRequest>): void

Unsubscribes from descriptor write request events.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value is descriptorWrite, which indicates a descriptor write request event.
callbackCallback<DescriptorWriteRequest>NoCallback for the descriptor write request event. If this parameter is not set, this API unsubscribes from all callbacks corresponding to type.

Example

import { BusinessError } from '@ohos.base';
try {
let gattServer: ble.GattServer = ble.createGattServer();
gattServer.off('descriptorWrite');
} catch (err) {
    console.error("errCode:" + (err as BusinessError).code + ",errMessage:" + (err as BusinessError).message);
}

on('connectionStateChange')

on(type: 'connectionStateChange', callback: Callback<BLEConnectionChangeState>): void

Subscribes to BLE connection state changes.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value is connectionStateChange, which indicates BLE connection state changes.
callbackCallback<BLEConnectionChangeState>YesCallback invoked to return the BLE connection state.

Example

import { BusinessError } from '@ohos.base';
import constant from '@ohos.bluetooth.constant';
function Connected(bleConnectionChangeState: ble.BLEConnectionChangeState) {
  let deviceId: string = bleConnectionChangeState.deviceId;
  let status: constant.ProfileConnectionState = bleConnectionChangeState.state;
}
try {
let gattServer: ble.GattServer = ble.createGattServer();
gattServer.on('connectionStateChange', Connected);
} catch (err) {
    console.error("errCode:" + (err as BusinessError).code + ",errMessage:" + (err as BusinessError).message);
}

off('connectionStateChange')

off(type: 'connectionStateChange', callback?: Callback<BLEConnectionChangeState>): void

Unsubscribes from BLE connection state changes.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value is connectionStateChange, which indicates BLE connection state changes.
callbackCallback<BLEConnectionChangeState>NoCallback for the BLE connection state change. If this parameter is not set, this API unsubscribes from all callbacks corresponding to type.

Example

import { BusinessError } from '@ohos.base';
try {
let gattServer: ble.GattServer = ble.createGattServer();
gattServer.off('connectionStateChange');
} catch (err) {
    console.error("errCode:" + (err as BusinessError).code + ",errMessage:" + (err as BusinessError).message);
}

on('BLEMtuChange')

on(type: 'BLEMtuChange', callback: Callback<number>): void

Subscribes to MTU status changes for the server.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value is BLEMtuChange, which indicates MTU status changes. If this parameter is not set correctly, the callback cannot be registered.
callbackCallback<number>YesCallback invoked to return the number of MTU bytes.

Example

import { BusinessError } from '@ohos.base';
try {
    let gattServer: ble.GattServer = ble.createGattServer();
    gattServer.on('BLEMtuChange', (mtu: number) => {
      console.info('BLEMtuChange, mtu: ' + mtu);
    });
} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

off('BLEMtuChange')

off(type: 'BLEMtuChange', callback?: Callback<number>): void

Unsubscribes from MTU status changes for the server.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value is BLEMtuChange, which indicates MTU status changes. If this parameter is not set correctly, the callback cannot be unregistered.
callbackCallback<number>NoCallback for the MTU status changes. If this parameter is not set, this API unsubscribes from all callbacks corresponding to type.

Example

import { BusinessError } from '@ohos.base';
try {
    let gattServer: ble.GattServer = ble.createGattServer();
    gattServer.off('BLEMtuChange');
} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

GattClientDevice

Implements the GATT client. Before using an API of this class, you must create a GattClientDevice instance using createGattClientDevice(deviceId: string).

connect

connect(): void

Connects to the remote BLE device.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Error codes

For details about the error codes, see Bluetooth Error Codes.

IDError Message
2900001Service stopped.
2900003Bluetooth switch is off.
2900099Operation failed.

Example

import { BusinessError } from '@ohos.base';
try {
    let device: ble.GattClientDevice = ble.createGattClientDevice('XX:XX:XX:XX:XX:XX');
    device.connect();
} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

disconnect

disconnect(): void

Disconnects from the remote BLE device.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Error codes

For details about the error codes, see Bluetooth Error Codes.

IDError Message
2900001Service stopped.
2900003Bluetooth switch is off.
2900099Operation failed.

Example

import { BusinessError } from '@ohos.base';
try {
    let device: ble.GattClientDevice = ble.createGattClientDevice('XX:XX:XX:XX:XX:XX');
    device.disconnect();
} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

close

close(): void

Closes this GATT client to unregister it from the protocol stack. The closed GattClientDevice instance will no longer be used.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Error codes

For details about the error codes, see Bluetooth Error Codes.

IDError Message
2900001Service stopped.
2900003Bluetooth switch is off.
2900099Operation failed.

Example

import { BusinessError } from '@ohos.base';
try {
    let device: ble.GattClientDevice = ble.createGattClientDevice('XX:XX:XX:XX:XX:XX');
    device.close();
} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

getDeviceName

getDeviceName(callback: AsyncCallback<string>): void

Obtains the name of the remote BLE device. This API uses an asynchronous callback to return the result.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
callbackAsyncCallback<string>YesCallback invoked to return the remote BLE device name obtained.

Error codes

For details about the error codes, see Bluetooth Error Codes.

IDError Message
2900001Service stopped.
2900099Operation failed.

Example

import { BusinessError } from '@ohos.base';
// callback
try {
    let gattClient: ble.GattClientDevice = ble.createGattClientDevice("XX:XX:XX:XX:XX:XX");
    gattClient.connect();
    gattClient.getDeviceName((err: BusinessError, data: string)=> {
        console.info('device name err ' + JSON.stringify(err));
        console.info('device name' + JSON.stringify(data));
    })
} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

getDeviceName

getDeviceName(): Promise<string>

Obtains the name of the remote BLE device. This API uses a promise to return the result.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Return value

TypeDescription
Promise<string>Promise used to return the remote BLE device name.

Error codes

For details about the error codes, see Bluetooth Error Codes.

IDError Message
2900001Service stopped.
2900099Operation failed.

Example

import { BusinessError } from '@ohos.base';
// promise
try {
    let gattClient: ble.GattClientDevice = ble.createGattClientDevice("XX:XX:XX:XX:XX:XX");
    gattClient.connect();
    gattClient.getDeviceName().then((data: string) => {
        console.info('device name' + JSON.stringify(data));
    })
} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

getServices

getServices(callback: AsyncCallback<Array<GattService>>): void

Obtains all services of the remote BLE device. This API uses an asynchronous callback to return the result.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
callbackAsyncCallback<Array<GattService>>YesCallback invoked to return the services obtained.

Error codes

For details about the error codes, see Bluetooth Error Codes.

IDError Message
2900001Service stopped.
2900099Operation failed.

Example

import { BusinessError } from '@ohos.base';
// Callback
function getServices(code: BusinessError, gattServices: Array<ble.GattService>) {
  if (code.code == 0) {
      let services: Array<ble.GattService> = 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);
      }
  }
}

try {
    let device: ble.GattClientDevice = ble.createGattClientDevice('XX:XX:XX:XX:XX:XX');
    device.connect();
    device.getServices(getServices);
} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

getServices

getServices(): Promise<Array<GattService>>

Obtains all services of the remote BLE device. This API uses a promise to return the result.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Return value

TypeDescription
Promise<Array<GattService>>Promise used to return the services obtained.

Error codes

For details about the error codes, see Bluetooth Error Codes.

IDError Message
2900001Service stopped.
2900099Operation failed.

Example

import { BusinessError } from '@ohos.base';
// Promise
try {
    let device: ble.GattClientDevice = ble.createGattClientDevice('XX:XX:XX:XX:XX:XX');
    device.connect();
    device.getServices().then((result: Array<ble.GattService>) => {
        console.info('getServices successfully:' + JSON.stringify(result));
    });
} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

readCharacteristicValue

readCharacteristicValue(characteristic: BLECharacteristic, callback: AsyncCallback<BLECharacteristic>): void

Reads the characteristic value of the specific service of the remote BLE device. This API uses an asynchronous callback to return the result.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
characteristicBLECharacteristicYesCharacteristic value to read.
callbackAsyncCallback<BLECharacteristic>YesCallback invoked to return the characteristic value read.

Error codes

For details about the error codes, see Bluetooth Error Codes.

IDError Message
2900001Service stopped.
2901000Read forbidden.
2900099Operation failed.

Example

import { BusinessError } from '@ohos.base';
function readCcc(code: BusinessError, BLECharacteristic: ble.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 descriptors: Array<ble.BLEDescriptor> = [];
let bufferDesc = new ArrayBuffer(8);
let descV = new Uint8Array(bufferDesc);
descV[0] = 11;
let descriptor: ble.BLEDescriptor = {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: ble.BLECharacteristic = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB',
characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB',
characteristicValue: bufferCCC, descriptors:descriptors};

try {
    let device: ble.GattClientDevice = ble.createGattClientDevice('XX:XX:XX:XX:XX:XX');
    device.readCharacteristicValue(characteristic, readCcc);
} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

readCharacteristicValue

readCharacteristicValue(characteristic: BLECharacteristic): Promise<BLECharacteristic>

Reads the characteristic value of the specific service of the remote BLE device. This API uses a promise to return the result.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
characteristicBLECharacteristicYesCharacteristic value to read.

Return value

TypeDescription
Promise<BLECharacteristic>Promise used to return the characteristic value read.

Error codes

For details about the error codes, see Bluetooth Error Codes.

IDError Message
2900001Service stopped.
2901000Read forbidden.
2900099Operation failed.

Example

import { BusinessError } from '@ohos.base';
let descriptors: Array<ble.BLEDescriptor> = [];
let bufferDesc = new ArrayBuffer(8);
let descV = new Uint8Array(bufferDesc);
descV[0] = 11;
let descriptor: ble.BLEDescriptor = {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: ble.BLECharacteristic = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB',
characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB',
characteristicValue: bufferCCC, descriptors:descriptors};

try {
    let device: ble.GattClientDevice = ble.createGattClientDevice('XX:XX:XX:XX:XX:XX');
    device.readCharacteristicValue(characteristic);
} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

readDescriptorValue

readDescriptorValue(descriptor: BLEDescriptor, callback: AsyncCallback<BLEDescriptor>): void

Reads the descriptor contained in the specific characteristic of the remote BLE device. This API uses an asynchronous callback to return the result.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
descriptorBLEDescriptorYesDescriptor to read.
callbackAsyncCallback<BLEDescriptor>YesCallback invoked to return the descriptor read.

Error codes

For details about the error codes, see Bluetooth Error Codes.

IDError Message
2900001Service stopped.
2901000Read forbidden.
2900099Operation failed.

Example

import { BusinessError } from '@ohos.base';
function readDesc(code: BusinessError, BLEDescriptor: ble.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 bufferDesc = new ArrayBuffer(8);
let descV = new Uint8Array(bufferDesc);
descV[0] = 11;
let descriptor: ble.BLEDescriptor = {
    serviceUuid: '00001810-0000-1000-8000-00805F9B34FB',
    characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB',
    descriptorUuid: '00002903-0000-1000-8000-00805F9B34FB',
    descriptorValue: bufferDesc
};
try {
    let device: ble.GattClientDevice = ble.createGattClientDevice('XX:XX:XX:XX:XX:XX');
    device.readDescriptorValue(descriptor, readDesc);
} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

readDescriptorValue

readDescriptorValue(descriptor: BLEDescriptor): Promise<BLEDescriptor>

Reads the descriptor contained in the specific characteristic of the remote BLE device. This API uses a promise to return the result.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
descriptorBLEDescriptorYesDescriptor to read.

Return value

TypeDescription
Promise<BLEDescriptor>Promise used to return the descriptor read.

Error codes

For details about the error codes, see Bluetooth Error Codes.

IDError Message
2900001Service stopped.
2901000Read forbidden.
2900099Operation failed.

Example

import { BusinessError } from '@ohos.base';
let bufferDesc = new ArrayBuffer(8);
let descV = new Uint8Array(bufferDesc);
descV[0] = 11;
let descriptor: ble.BLEDescriptor = {
    serviceUuid: '00001810-0000-1000-8000-00805F9B34FB',
    characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB',
    descriptorUuid: '00002903-0000-1000-8000-00805F9B34FB',
    descriptorValue: bufferDesc
};
try {
    let device: ble.GattClientDevice = ble.createGattClientDevice('XX:XX:XX:XX:XX:XX');
    device.readDescriptorValue(descriptor);
} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

writeCharacteristicValue

writeCharacteristicValue(characteristic: BLECharacteristic, writeType: GattWriteType, callback: AsyncCallback<void>): void

Writes a characteristic value to the remote BLE device.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
characteristicBLECharacteristicYesBinary value and other parameters of the BLE device characteristic.
writeTypeGattWriteTypeYesWrite type of the Bluetooth device characteristic value.
callbackAsyncCallback<void>YesCallback invoked to return the result. If the write operation is successful, err is undefined. Otherwise, err is an error object.

Error codes

For details about the error codes, see Bluetooth Error Codes.

IDError Message
2900001Service stopped.
2901001Write forbidden.
2900099Operation failed.

Example

import { BusinessError } from '@ohos.base';
let descriptors: Array<ble.BLEDescriptor> = [];
let bufferDesc = new ArrayBuffer(8);
let descV = new Uint8Array(bufferDesc);
descV[0] = 11;
let descriptor: ble.BLEDescriptor = {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: ble.BLECharacteristic = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB',
  characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB',
  characteristicValue: bufferCCC, descriptors:descriptors};
function writeCharacteristicValueCallBack(code: BusinessError) {
    if (code.code != 0) {
        return;
    }
    console.log('bluetooth writeCharacteristicValue success');
}
try {
    let device: ble.GattClientDevice = ble.createGattClientDevice('XX:XX:XX:XX:XX:XX');
    device.writeCharacteristicValue(characteristic, ble.GattWriteType.WRITE, writeCharacteristicValueCallBack);
} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

writeCharacteristicValue

writeCharacteristicValue(characteristic: BLECharacteristic, writeType: GattWriteType): Promise<void>

Writes a characteristic value to the remote BLE device.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
characteristicBLECharacteristicYesBinary value and other parameters of the BLE device characteristic.
writeTypeGattWriteTypeYesWrite type of the Bluetooth device characteristic value.

Return value

TypeDescription
Promise<void>Promise used to return the descriptor read.

Error codes

For details about the error codes, see Bluetooth Error Codes.

IDError Message
2900001Service stopped.
2901001Write forbidden.
2900099Operation failed.

Example

import { BusinessError } from '@ohos.base';
let descriptors: Array<ble.BLEDescriptor>  = [];
let bufferDesc = new ArrayBuffer(8);
let descV = new Uint8Array(bufferDesc);
descV[0] = 11;
let descriptor: ble.BLEDescriptor = {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: ble.BLECharacteristic = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB',
  characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB',
  characteristicValue: bufferCCC, descriptors:descriptors};
try {
    let device: ble.GattClientDevice = ble.createGattClientDevice('XX:XX:XX:XX:XX:XX');
    device.writeCharacteristicValue(characteristic, ble.GattWriteType.WRITE);
} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

writeDescriptorValue

writeDescriptorValue(descriptor: BLEDescriptor, callback: AsyncCallback<void>): void

Writes binary data to the specific descriptor of the remote BLE device.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
descriptorBLEDescriptorYesBinary value and other parameters of the BLE device descriptor.
callbackAsyncCallback<void>YesCallback invoked to return the result. If the write operation is successful, err is undefined. Otherwise, err is an error object.

Error codes

For details about the error codes, see Bluetooth Error Codes.

IDError Message
2900001Service stopped.
2901001Write forbidden.
2900099Operation failed.

Example

import { BusinessError } from '@ohos.base';
let bufferDesc = new ArrayBuffer(8);
let descV = new Uint8Array(bufferDesc);
descV[0] = 22;
let descriptor: ble.BLEDescriptor = {
    serviceUuid: '00001810-0000-1000-8000-00805F9B34FB',
    characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB',
    descriptorUuid: '00002903-0000-1000-8000-00805F9B34FB',
    descriptorValue: bufferDesc
};
try {
    let device: ble.GattClientDevice = ble.createGattClientDevice('XX:XX:XX:XX:XX:XX');
    device.writeDescriptorValue(descriptor);
} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

writeDescriptorValue

writeDescriptorValue(descriptor: BLEDescriptor): Promise<void>

Writes binary data to the specific descriptor of the remote BLE device.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
descriptorBLEDescriptorYesBinary value and other parameters of the BLE device descriptor.

Return value

TypeDescription
Promise<void>Promise used to return the descriptor read.

Error codes

For details about the error codes, see Bluetooth Error Codes.

IDError Message
2900001Service stopped.
2901001Write forbidden.
2900099Operation failed.

Example

import { BusinessError } from '@ohos.base';
let bufferDesc = new ArrayBuffer(8);
let descV = new Uint8Array(bufferDesc);
descV[0] = 22;
let descriptor: ble.BLEDescriptor = {
    serviceUuid: '00001810-0000-1000-8000-00805F9B34FB',
    characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB',
    descriptorUuid: '00002903-0000-1000-8000-00805F9B34FB',
    descriptorValue: bufferDesc
};
try {
    let device: ble.GattClientDevice = ble.createGattClientDevice('XX:XX:XX:XX:XX:XX');
    device.writeDescriptorValue(descriptor);
} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

getRssiValue

getRssiValue(callback: AsyncCallback<number>): void

Obtains the RSSI of the remote BLE device. This API uses an asynchronous callback to return the result. It can be used only after a connection is set up by calling connect.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
callbackAsyncCallback<number>YesCallback invoked to return the RSSI, in dBm.

Error codes

For details about the error codes, see Bluetooth Error Codes.

IDError Message
2900099Operation failed.

Example

import { BusinessError } from '@ohos.base';
// callback
try {
    let gattClient: ble.GattClientDevice = ble.createGattClientDevice("XX:XX:XX:XX:XX:XX");
    gattClient.connect();
    let rssi = gattClient.getRssiValue((err: BusinessError, data: number)=> {
        console.info('rssi err ' + JSON.stringify(err));
        console.info('rssi value' + JSON.stringify(data));
    })
} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

getRssiValue

getRssiValue(): Promise<number>

Obtains the RSSI of the remote BLE device. This API uses a promise to return the result. It can be used only after a connection is set up by calling connect.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Return value

TypeDescription
Promise<number>Promise used to return the RSSI, in dBm.

Error codes

For details about the error codes, see Bluetooth Error Codes.

IDError Message
2900099Operation failed.

Example

import { BusinessError } from '@ohos.base';
// promise
try {
    let gattClient: ble.GattClientDevice = ble.createGattClientDevice("XX:XX:XX:XX:XX:XX");
    gattClient.getRssiValue().then((data: number) => {
        console.info('rssi' + JSON.stringify(data));
    })
} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

setBLEMtuSize

setBLEMtuSize(mtu: number): void

Sets the maximum transmission unit (MTU) that can be transmitted between the GATT client and its remote BLE device. This API can be used only after a connection is set up by calling connect.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
mtunumberYesMTU to set, which ranges from 22 to 512 bytes.

Error codes

For details about the error codes, see Bluetooth Error Codes.

IDError Message
2900001Service stopped.
2900099Operation failed.

Example

import { BusinessError } from '@ohos.base';
try {
    let device: ble.GattClientDevice = ble.createGattClientDevice('XX:XX:XX:XX:XX:XX');
    device.setBLEMtuSize(128);
} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

setCharacteristicChangeNotification

setCharacteristicChangeNotification(characteristic: BLECharacteristic, enable: boolean, callback: AsyncCallback<void>): void

Sets the function of notifying the GATT client when the characteristic value of the remote BLE device changes.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
characteristicBLECharacteristicYesBLE characteristic to listen for.
enablebooleanYesWhether to enable the notify function. The value true means to enable the notify function, and the value false means the opposite.
callbackAsyncCallback<void>YesCallback invoked to return the result. If the operation is successful, err is undefined. Otherwise, err is an error object.

Error codes

For details about the error codes, see Bluetooth Error Codes.

IDError Message
2900001Service stopped.
2900099Operation failed.

Example

import { BusinessError } from '@ohos.base';
// Create descriptors.
let descriptors: Array<ble.BLEDescriptor> = [];
let arrayBuffer = new ArrayBuffer(8);
let descV = new Uint8Array(arrayBuffer);
descV[0] = 11;
let descriptor: ble.BLEDescriptor = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB',
  characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB',
  descriptorUuid: '00002902-0000-1000-8000-00805F9B34FB', descriptorValue: arrayBuffer};
descriptors[0] = descriptor;
let arrayBufferC = new ArrayBuffer(8);
let characteristic: ble.BLECharacteristic = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB',
  characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', characteristicValue: arrayBufferC, descriptors:descriptors};
try {
    let device: ble.GattClientDevice = ble.createGattClientDevice('XX:XX:XX:XX:XX:XX');
    device.setCharacteristicChangeNotification(characteristic, false);
} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

setCharacteristicChangeNotification

setCharacteristicChangeNotification(characteristic: BLECharacteristic, enable: boolean): Promise<void>

Sets the function of notifying the GATT client when the characteristic value of the remote BLE device changes.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
characteristicBLECharacteristicYesBLE characteristic to listen for.
enablebooleanYesWhether to enable the notify function. The value true means to enable the notify function, and the value false means the opposite.

Return value

TypeDescription
Promise<void>Promise used to return the result.

Error codes

For details about the error codes, see Bluetooth Error Codes.

IDError Message
2900001Service stopped.
2900099Operation failed.

Example

import { BusinessError } from '@ohos.base';
// Create descriptors.
let descriptors: Array<ble.BLEDescriptor> = [];
let arrayBuffer = new ArrayBuffer(8);
let descV = new Uint8Array(arrayBuffer);
descV[0] = 11;
let descriptor: ble.BLEDescriptor = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB',
  characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB',
  descriptorUuid: '00002902-0000-1000-8000-00805F9B34FB', descriptorValue: arrayBuffer};
descriptors[0] = descriptor;
let arrayBufferC = new ArrayBuffer(8);
let characteristic: ble.BLECharacteristic = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB',
  characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', characteristicValue: arrayBufferC, descriptors:descriptors};
try {
    let device: ble.GattClientDevice = ble.createGattClientDevice('XX:XX:XX:XX:XX:XX');
    device.setCharacteristicChangeNotification(characteristic, false);
} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

setCharacteristicChangeIndication

setCharacteristicChangeIndication(characteristic: BLECharacteristic, enable: boolean, callback: AsyncCallback<void>): void

Sets the function of notifying the GATT client when the characteristic value of the remote BLE device changes.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
characteristicBLECharacteristicYesBLE characteristic to listen for.
enablebooleanYesWhether to enable the notify function. The value true means to enable the notify function, and the value false means the opposite.
callbackAsyncCallback<void>YesCallback invoked to return the result. If the operation is successful, err is undefined. Otherwise, err is an error object.

Return value

TypeDescription
Promise<void>Promise used to return the result.

Error codes

For details about the error codes, see Bluetooth Error Codes.

IDError Message
2900001Service stopped.
2900099Operation failed.

Example

import { BusinessError } from '@ohos.base';
// Create descriptors.
let descriptors: Array<ble.BLEDescriptor> = [];
let arrayBuffer = new ArrayBuffer(8);
let descV = new Uint8Array(arrayBuffer);
descV[0] = 11;
let descriptor: ble.BLEDescriptor = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB',
  characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB',
  descriptorUuid: '00002902-0000-1000-8000-00805F9B34FB', descriptorValue: arrayBuffer};
descriptors[0] = descriptor;
let arrayBufferC = new ArrayBuffer(8);
let characteristic: ble.BLECharacteristic = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB',
  characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', characteristicValue: arrayBufferC, descriptors:descriptors};
try {
    let device: ble.GattClientDevice = ble.createGattClientDevice('XX:XX:XX:XX:XX:XX');
    device.setCharacteristicChangeIndication(characteristic, false);
} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

setCharacteristicChangeIndication

setCharacteristicChangeIndication(characteristic: BLECharacteristic, enable: boolean): Promise<void>

Sets the function of notifying the GATT client when the characteristic value of the remote BLE device changes.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
characteristicBLECharacteristicYesBLE characteristic to listen for.
enablebooleanYesWhether to enable the notify function. The value true means to enable the notify function, and the value false means the opposite.

Return value

TypeDescription
Promise<void>Promise used to return the result.

Error codes

For details about the error codes, see Bluetooth Error Codes.

IDError Message
2900001Service stopped.
2900099Operation failed.

Example

import { BusinessError } from '@ohos.base';
// Create descriptors.
let descriptors: Array<ble.BLEDescriptor> = [];
let arrayBuffer = new ArrayBuffer(8);
let descV = new Uint8Array(arrayBuffer);
descV[0] = 11;
let descriptor: ble.BLEDescriptor = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB',
  characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB',
  descriptorUuid: '00002902-0000-1000-8000-00805F9B34FB', descriptorValue: arrayBuffer};
descriptors[0] = descriptor;
let arrayBufferC = new ArrayBuffer(8);
let characteristic: ble.BLECharacteristic = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB',
  characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', characteristicValue: arrayBufferC, descriptors:descriptors};
try {
    let device: ble.GattClientDevice = ble.createGattClientDevice('XX:XX:XX:XX:XX:XX');
    device.setCharacteristicChangeIndication(characteristic, false);
} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

on('BLECharacteristicChange')

on(type: 'BLECharacteristicChange', callback: Callback<BLECharacteristic>): void

Subscribes to BLE characteristic changes. The client can receive a notification from the server only after the setNotifyCharacteristicChanged method is called.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value is BLECharacteristicChange, which indicates characteristic value changes.
callbackCallback<BLECharacteristic>YesCallback invoked to return the characteristic value changes.

Example

import { BusinessError } from '@ohos.base';
function CharacteristicChange(characteristicChangeReq: ble.BLECharacteristic) {
    let serviceUuid: string = characteristicChangeReq.serviceUuid;
    let characteristicUuid: string = characteristicChangeReq.characteristicUuid;
    let value: Uint8Array = new Uint8Array(characteristicChangeReq.characteristicValue);
}
try {
    let device: ble.GattClientDevice = ble.createGattClientDevice('XX:XX:XX:XX:XX:XX');
    device.on('BLECharacteristicChange', CharacteristicChange);
} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

off('BLECharacteristicChange')

off(type: 'BLECharacteristicChange', callback?: Callback<BLECharacteristic>): void

Unsubscribes from BLE characteristic changes.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value is BLECharacteristicChange, which indicates characteristic value changes.
callbackCallback<BLECharacteristic>NoCallback for the characteristic value change. If this parameter is not set, this API unsubscribes from all callbacks corresponding to type.

Example

import { BusinessError } from '@ohos.base';
try {
    let device: ble.GattClientDevice = ble.createGattClientDevice('XX:XX:XX:XX:XX:XX');
    device.off('BLECharacteristicChange');
} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

on('BLEConnectionStateChange')

on(type: 'BLEConnectionStateChange', callback: Callback<BLEConnectionChangeState>): void

Subscribes to BLE connection state changes.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value is BLEConnectionStateChange, which indicates BLE connection state changes.
callbackCallback<BLEConnectionChangeState>YesCallback invoked to return the BLE connection state.

Example

import { BusinessError } from '@ohos.base';
function ConnectStateChanged(state: ble.BLEConnectionChangeState) {
  console.log('bluetooth connect state changed');
  let connectState: ble.ProfileConnectionState = state.state;
}
try {
    let device: ble.GattClientDevice = ble.createGattClientDevice('XX:XX:XX:XX:XX:XX');
    device.on('BLEConnectionStateChange', ConnectStateChanged);
} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

off('BLEConnectionStateChange')

off(type: 'BLEConnectionStateChange', callback?: Callback<BLEConnectionChangeState>): void

Unsubscribes from BLE connection state changes.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value is BLEConnectionStateChange, which indicates BLE connection state changes.
callbackCallback<BLEConnectionChangeState>NoCallback for the BLE connection state change. If this parameter is not set, this API unsubscribes from all callbacks corresponding to type.

Example

import { BusinessError } from '@ohos.base';
try {
    let device: ble.GattClientDevice = ble.createGattClientDevice('XX:XX:XX:XX:XX:XX');
    device.off('BLEConnectionStateChange');
} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

on('BLEMtuChange')

on(type: 'BLEMtuChange', callback: Callback<number>): void

Subscribes to MTU status changes for the client.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value is BLEMtuChange, which indicates MTU status changes. If this parameter is not set correctly, the callback cannot be registered.
callbackCallback<number>YesCallback invoked to return the number of MTU bytes.

Example

import { BusinessError } from '@ohos.base';
try {
    let gattClient: ble.GattClientDevice = ble.createGattClientDevice('XX:XX:XX:XX:XX:XX');
    gattClient.on('BLEMtuChange', (mtu: number) => {
      console.info('BLEMtuChange, mtu: ' + mtu);
    });
} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

off('BLEMtuChange')

off(type: 'BLEMtuChange', callback?: Callback<number>): void

Unsubscribes from MTU status changes for the client.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value is BLEMtuChange, which indicates MTU status changes. If this parameter is not set correctly, the callback cannot be unregistered.
callbackCallback<number>NoCallback for the MTU status changes. If this parameter is not set, this API unsubscribes from all callbacks corresponding to type.

Example

import { BusinessError } from '@ohos.base';
try {
    let device: ble.GattClientDevice = ble.createGattClientDevice('XX:XX:XX:XX:XX:XX');
    device.off('BLEMtuChange');
} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

GattService

Defines the GATT service API parameters.

System capability: SystemCapability.Communication.Bluetooth.Core

NameTypeReadableWritableDescription
serviceUuidstringYesYesUUID of the service, for example, 00001888-0000-1000-8000-00805f9b34fb.
isPrimarybooleanYesYesWhether the service is a primary service. The value true means a primary service.
characteristicsArray<BLECharacteristic>YesYesList of characteristics of the service.
includeServicesArray<GattService>YesYesServices on which the service depends.

BLECharacteristic

Defines the characteristic API parameters.

System capability: SystemCapability.Communication.Bluetooth.Core

NameTypeReadableWritableDescription
serviceUuidstringYesYesUUID of the service, for example, 00001888-0000-1000-8000-00805f9b34fb.
characteristicUuidstringYesYesUUID of the characteristic, for example, 00002a11-0000-1000-8000-00805f9b34fb.
characteristicValueArrayBufferYesYesBinary value of the characteristic.
descriptorsArray<BLEDescriptor>YesYesList of descriptors of the characteristic.
propertiesGattPropertiesYesYesProperties of the characteristic.

BLEDescriptor

Defines the BLE descriptor.

System capability: SystemCapability.Communication.Bluetooth.Core

NameTypeReadableWritableDescription
serviceUuidstringYesYesUUID of the service, for example, 00001888-0000-1000-8000-00805f9b34fb.
characteristicUuidstringYesYesUUID of the characteristic, for example, 00002a11-0000-1000-8000-00805f9b34fb.
descriptorUuidstringYesYesUUID of the descriptor, for example, 00002902-0000-1000-8000-00805f9b34fb.
descriptorValueArrayBufferYesYesBinary value of the descriptor.

NotifyCharacteristic

Defines the parameters in the notifications sent when the server characteristic value changes.

System capability: SystemCapability.Communication.Bluetooth.Core

NameTypeReadableWritableDescription
serviceUuidstringYesYesUUID of the service, for example, 00001888-0000-1000-8000-00805f9b34fb.
characteristicUuidstringYesYesUUID of the characteristic, for example, 00002a11-0000-1000-8000-00805f9b34fb.
characteristicValueArrayBufferYesYesBinary value of the characteristic.
confirmbooleanYesYesWhether the notification needs to be confirmed by the remote end. For a notification, set it to true. In this case, the remote end must confirm the receipt of the notification. For an indication, set it to false. In this case, the remote end does not need to confirm the receipt of the notification.

CharacteristicReadRequest

Defines the parameters of the CharacteristicReadReq event received by the server.

System capability: SystemCapability.Communication.Bluetooth.Core

NameTypeReadableWritableDescription
deviceIdstringYesNoAddress of the remote device that sends the CharacteristicReadReq event, for example, XX:XX:XX:XX:XX:XX.
transIdnumberYesNoTransmission ID of the read request. The response returned by the server must use the same transmission ID.
offsetnumberYesNoPosition 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.
characteristicUuidstringYesNoUUID of the characteristic, for example, 00002a11-0000-1000-8000-00805f9b34fb.
serviceUuidstringYesNoUUID of the service, for example, 00001888-0000-1000-8000-00805f9b34fb.

CharacteristicWriteRequest

Defines the parameters of the CharacteristicWriteReq event received by the server.

System capability: SystemCapability.Communication.Bluetooth.Core

NameTypeReadableWritableDescription
deviceIdstringYesNoAddress of the remote device that sends the CharacteristicWriteReq event, for example, XX:XX:XX:XX:XX:XX.
transIdnumberYesNoTransmission ID of the write request. The response returned by the server must use the same transmission ID.
offsetnumberYesNoStart 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.
isPreparedbooleanYesNoWhether the write request is executed immediately.
needRspbooleanYesNoWhether to send a response to the GATT client.
valueArrayBufferYesNoBinary value of the descriptor to write.
characteristicUuidstringYesNoUUID of the characteristic, for example, 00002a11-0000-1000-8000-00805f9b34fb.
serviceUuidstringYesNoUUID of the service, for example, 00001888-0000-1000-8000-00805f9b34fb.

DescriptorReadRequest

Defines the parameters of the DescriptorReadReq event received by the server.

System capability: SystemCapability.Communication.Bluetooth.Core

NameTypeReadableWritableDescription
deviceIdstringYesNoAddress of the remote device that sends a DescriptorReadReq event, for example, XX:XX:XX:XX:XX:XX.
transIdnumberYesNoTransmission ID of the read request. The response returned by the server must use the same transmission ID.
offsetnumberYesNoPosition 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.
descriptorUuidstringYesNoUUID of the descriptor, for example, 00002902-0000-1000-8000-00805f9b34fb.
characteristicUuidstringYesNoUUID of the characteristic, for example, 00002a11-0000-1000-8000-00805f9b34fb.
serviceUuidstringYesNoUUID of the service, for example, 00001888-0000-1000-8000-00805f9b34fb.

DescriptorWriteRequest

Defines the parameters of the DescriptorWriteReq event received by the server.

System capability: SystemCapability.Communication.Bluetooth.Core

NameTypeReadableWritableDescription
deviceIdstringYesNoAddress of the remote device that sends a DescriptorWriteReq event, for example, XX:XX:XX:XX:XX:XX.
transIdnumberYesNoTransmission ID of the write request. The response returned by the server must use the same transmission ID.
offsetnumberYesNoStart 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.
isPreparedbooleanYesNoWhether the write request is executed immediately.
needRspbooleanYesNoWhether to send a response to the GATT client.
valueArrayBufferYesNoBinary value of the descriptor to write.
descriptorUuidstringYesNoUUID of the descriptor, for example, 00002902-0000-1000-8000-00805f9b34fb.
characteristicUuidstringYesNoUUID of the characteristic, for example, 00002a11-0000-1000-8000-00805f9b34fb.
serviceUuidstringYesNoUUID 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.

System capability: SystemCapability.Communication.Bluetooth.Core

NameTypeReadableWritableDescription
deviceIdstringYesNoAddress of the remote device, for example, XX:XX:XX:XX:XX:XX.
transIdnumberYesNoTransmission ID of the request. The value must be the same as the ID carried in the read/write request received.
statusnumberYesNoResponse state. Set this parameter to 0, which indicates a normal response.
offsetnumberYesNoStart read/write position. The value must be the same as the offset carried in the read/write request.
valueArrayBufferYesNoBinary data in the response.

BLEConnectionChangeState

Defines the parameters of BLEConnectChangedState.

System capability: SystemCapability.Communication.Bluetooth.Core

NameTypeReadableWritableDescription
deviceIdstringYesNoAddress of the remote device, for example, XX:XX:XX:XX:XX:XX.
stateProfileConnectionStateYesYesBLE connection state.

ScanResult

Defines the scan result.

System capability: SystemCapability.Communication.Bluetooth.Core

NameTypeReadableWritableDescription
deviceIdstringYesNoAddress of the scanned device, for example, XX:XX:XX:XX:XX:XX.
rssinumberYesNoRSSI of the device.
dataArrayBufferYesNoAdvertisement packets sent by the device.
deviceNamestringYesNoName of the device detected.
connectablebooleanYesNoWhether the discovered device is connectable.

AdvertiseSetting

Defines the BLE advertising parameters.

System capability: SystemCapability.Communication.Bluetooth.Core

NameTypeReadableWritableDescription
intervalnumberYesYesInterval for BLE advertising. The minimum value is 32 slots (20 ms). The maximum value is 16384 slots. The default value is 1600 slots (1s).
txPowernumberYesYesTransmit power, in dBm. The value range is -127 to 1. The default value is -7.
connectablebooleanYesYesWhether the advertisement is connectable. The default value is true.

AdvertiseData

Defines the content of a BLE advertisement packet.

System capability: SystemCapability.Communication.Bluetooth.Core

NameTypeReadableWritableDescription
serviceUuidsArray<string>YesYesList of service UUIDs to broadcast.
manufactureDataArray<ManufactureData>YesYesList of manufacturers to broadcast.
serviceDataArray<ServiceData>YesYesList of service data to broadcast.
includeDeviceNamebooleanYesYesWhether the device name is contained. This parameter is optional.

ManufactureData

Defines the content of a BLE advertisement packet.

System capability: SystemCapability.Communication.Bluetooth.Core

NameTypeReadableWritableDescription
manufactureIdnumberYesYesManufacturer ID allocated by the Bluetooth SIG.
manufactureValueArrayBufferYesYesManufacturer data.

ServiceData

Defines the service data contained in an advertisement packet.

System capability: SystemCapability.Communication.Bluetooth.Core

NameTypeReadableWritableDescription
serviceUuidstringYesYesService UUID.
serviceValueArrayBufferYesYesService data.

ScanFilter

Defines the scan filter parameters.

System capability: SystemCapability.Communication.Bluetooth.Core

NameTypeReadableWritableDescription
deviceIdstringYesYesAddress of the BLE device to filter, for example, XX:XX:XX:XX:XX:XX.
namestringYesYesName of the BLE device to filter.
serviceUuidstringYesYesService UUID of the device to filter, for example, 00001888-0000-1000-8000-00805f9b34fb.
serviceUuidMaskstringYesYesService UUID mask of the device to filter, for example, FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF.
serviceSolicitationUuidstringYesYesService solicitation UUID of the device to filter, for example, 00001888-0000-1000-8000-00805F9B34FB.
serviceSolicitationUuidMaskstringYesYesService solicitation UUID mask of the device to filter, for example, FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF.
serviceDataArrayBufferYesYesService data of the device to filter, for example, [0x90, 0x00, 0xF1, 0xF2].
serviceDataMaskArrayBufferYesYesService data mask of the device to filter, for example, [0xFF,0xFF,0xFF,0xFF].
manufactureIdnumberYesYesManufacturer ID of the device to filter, for example, 0x0006.
manufactureDataArrayBufferYesYesManufacturer data of the device to filter, for example, [0x1F,0x2F,0x3F].
manufactureDataMaskArrayBufferYesYesManufacturer data mask of the device to filter, for example, [0xFF, 0xFF, 0xFF].

ScanOptions

Defines the scan configuration parameters.

System capability: SystemCapability.Communication.Bluetooth.Core

NameTypeReadableWritableDescription
intervalnumberYesYesDelay in reporting the scan result. The default value is 0.
dutyModeScanDutyYesYesScan duty. The default value is SCAN_MODE_LOW_POWER.
matchModeMatchModeYesYesHardware filtering match mode. The default value is MATCH_MODE_AGGRESSIVE.

GattProperties

Defines the properties of a GATT characteristic.

System capability: SystemCapability.Communication.Bluetooth.Core

NameTypeMandatoryDescription
writebooleanYesPermits writes of the characteristic value (with a response).
writeNoResponsebooleanYesPermits writes of the characteristic value (without a response).
readbooleanYesPermits reads of the characteristic value.
notifybooleanYesPermits notifications of the characteristic value.
indicatebooleanYesPermits notifications of the characteristic value without acknowledgement.

GattWriteType

Enumerates the GATT write types.

System capability: SystemCapability.Communication.Bluetooth.Core

NameValueDescription
WRITE1Write a characteristic value with a response from the peer device.
WRITE_NO_RESPONSE2Write characteristic value without a response from the peer device.

ScanDuty

Enumerates the scan duties.

System capability: SystemCapability.Communication.Bluetooth.Core

NameValueDescription
SCAN_MODE_LOW_POWER0Low-power mode, which is the default value.
SCAN_MODE_BALANCED1Balanced mode.
SCAN_MODE_LOW_LATENCY2Low-latency mode.

MatchMode

Enumerates the hardware match modes of BLE scan filters.

System capability: SystemCapability.Communication.Bluetooth.Core

NameValueDescription
MATCH_MODE_AGGRESSIVE1Hardware reports the scan result with a lower threshold of signal strength and few number of matches in a duration. This is the default value.
MATCH_MODE_STICKY2Hardware reports the scan result with a higher threshold of signal strength and sightings.

你可能感兴趣的鸿蒙文章

harmony 鸿蒙APIs

harmony 鸿蒙System Common Events (To Be Deprecated Soon)

harmony 鸿蒙System Common Events

harmony 鸿蒙API Reference Document Description

harmony 鸿蒙Enterprise Device Management Overview (for System Applications Only)

harmony 鸿蒙BundleStatusCallback

harmony 鸿蒙@ohos.bundle.innerBundleManager (innerBundleManager)

harmony 鸿蒙@ohos.distributedBundle (Distributed Bundle Management)

harmony 鸿蒙@ohos.bundle (Bundle)

harmony 鸿蒙@ohos.enterprise.EnterpriseAdminExtensionAbility (EnterpriseAdminExtensionAbility)

  • 所属分类: 后端技术
  • 本文标签: 软件 鸿蒙
  • 版权声明: 本文链接 https://seaxiang.com/blog/9136d7604b08488084b3560a8a116715