Development of HarmonyOS Learning Road - Network and Connection (Bluetooth Development 2)

BLE scan and broadcast

scene introduction

Through the open capabilities provided by BLE scanning and broadcasting, you can obtain peripheral devices, start or stop BLE scanning, and broadcasting according to the specified status.

Interface Description

Table 1  The main interface of the BLE central device management class BleCentralManager

interface name

Functional description

startScan(List<BleScanFilter> filters)

Perform a BLE Bluetooth scan and use filters to filter the results.

stopScan()

Stop BLE bluetooth scanning.

getDevicesByStates(int[] states)

Get connected peripherals based on status.

BleCentralManager(Context context, BleCentralManagerCallback callback)

Get the central device management object.

Table 2  The main interface of the central device management callback class BleCentralManagerCallback

interface name

Functional description

scanResultEvent​(BleScanResult result)

Callback for the result of scanning to BLE devices.

groupScanResultsEvent​(List<BleScanResult> scanResults)

Callback for the result of scanning a set of BLE devices.

scanFailedEvent​(int resultCode)

Callback for startup scan failure.

Table 3  Main interface of BleAdvertiser class and BleAdvertiseCallback class related to BLE broadcasting

interface name

Functional description

BleAdvertiser(Context context, BleAdvertiseCallback callback)

Used to get the broadcast operation object.

startAdvertising(BleAdvertiseSettings settings, BleAdvertiseData advData, BleAdvertiseData scanResponse)

For BLE broadcast, the first parameter is the broadcast parameter, the second is the broadcast data, and the third parameter is the response of the scan and broadcast data parameters.

stopAdvertising()

Stop BLE broadcasting.

startResultEvent(int result)

Broadcast callback result.

Central device for BLE scanning

  1. Before BLE scanning, you must inherit the BleCentralManagerCallback class to implement the scanResultEvent and scanFailedEvent callback functions to receive the scan results.
  2. Call the BleCentralManager(BleCentralManagerCallback callback) interface to obtain the central device management object.
  3. Get the scan filter, if the filter is empty, scan without the filter, then call startScan() to start scanning the BLE device, and get the scanned BLE device in the callback.
// 实现扫描回调
public class ScanCallback implements BleCentralManagerCallback{
    List<BleScanResult> results = new ArrayList<BleScanResult>();
    @Override
    public void scanResultEvent(BleScanResult resultCode) {
        // 对扫描结果进行处理
        results.add(resultCode);
    }
    @Override    
    public void scanFailedEvent(int resultCode) {        
        HiLog.warn(TAG,"Start Scan failed, Code: %{public}d", resultCode);    
    }
    @Override
    public void groupScanResultsEvent​(final List<BleScanResult> scanResults){
        // 对扫描结果进行处理
    }
}
// 获取中心设备管理对象
private ScanCallback centralManagerCallback = new ScanCallback();
private BleCentralManager centralManager = new BleCentralManager(context, centralManagerCallback);
// 创建扫描过滤器然后开始扫描
List<BleScanFilter> filters = new ArrayList<BleScanFilter>();
centralManager.startScan(filters);

Peripheral device doing BLE broadcasting

  1. Before BLE broadcasting, you need to inherit the advertiseCallback class to implement the startResultEvent callback to obtain the broadcast result.
  2. Call the interface BleAdvertiser(Context context, BleAdvertiseCallback callback) to obtain the advertisement object, and construct advertisement parameters and advertisement data.
  3. Call the startAdvertising(BleAdvertiseSettings settings, BleAdvertiseData advData, BleAdvertiseData scanResponse) interface to start BLE broadcasting.
// 实现BLE广播回调
private BleAdvertiseCallback advertiseCallback = new BleAdvertiseCallback() {
    @Override    
    public void startResultEvent(int result) {
        if(result == BleAdvertiseCallback.RESULT_SUCC){
            // 开始BLE广播成功
        }else {
            // 开始BLE广播失败
        }
    }
};
// 获取BLE广播对象
private BleAdvertiser advertiser = new BleAdvertiser(this,advertiseCallback);
// 创建BLE广播参数和数据
private BleAdvertiseData data = new BleAdvertiseData.Builder()           
                        .addServiceUuid(SequenceUuid.uuidFromString(Server_UUID)) // 添加服务的UUID                  
                        .addServiceData(SequenceUuid.uuidFromString(Server_UUID), new byte[]{0x11}) // 添加广播数据内容
                        .build();
private BleAdvertiseSettings advertiseSettings = new BleAdvertiseSettings.Builder()                        
                       .setConnectable(true) // 设置是否可连接广播
                       .setInterval(BleAdvertiseSettings.INTERVAL_SLOT_DEFAULT) // 设置广播间隔
                       .setTxPower(BleAdvertiseSettings.TX_POWER_DEFAULT) // 设置广播功率
                       .build();
// 开始广播
advertiser.startAdvertising(advertiseSettings, data, null);

BLE central device exchanges data with peripheral devices

scene introduction

The BLE peripheral device and the central device establish a GATT connection, through which the central device can obtain the Service, Characteristic​, Descriptor, RSSI and other data supported by the peripheral device. At the same time, the central device can request data from the peripheral device, and write characteristic value data such as Characteristic and Descriptor to the peripheral device.

Interface Description

The interface description of BlePeripheralDevice of the Bluetooth low energy peripheral device operation class is as follows.

Table 1  Introduction to the operation API of Bluetooth low energy peripheral devices

interface name

Functional description

connect(boolean isAutoConnect, BlePeripheralCallback callback)

Reconnect the GATT peripheral, isAutoConnect indicates whether to connect automatically.

discoverServices()

Search for services, characteristics and descriptions supported by peripherals.

getServices()

Get all GATT services supported by the peripheral.

getService(UUID uuid)

Obtain a GATT service supported by the peripheral based on the UUID.

disconnect()

Disconnect the BLE connection from the peripheral.

close()

Close the bluetooth GATT client.

readCharacteristic(GattCharacteristic characteristic)

Read peripheral device GATT characteristics.

writeCharacteristic(GattCharacteristic characteristic)

Writes the GATT characteristic value of the specified peripheral.

setNotifyCharacteristic(GattCharacteristic characteristic, boolean enable)

Set enable/disable of specified GATT feature notification.

readDescriptor (GattDescriptor descriptor)

Read peripheral device GATT description value.

writeDescriptor(GattDescriptor descriptor)

Writes the GATT description value of the specified peripheral.

readRemoteRssiValue()

Read the RSSI of a connected peripheral.

requestBleConnectionPriority(int connPriority)

Request link parameter update.

requestBleMtuSize(int mtu)

Requests the MTU size to use for a given connection.

The interface description of BlePeripheralCallback, the operation callback class of BlePeripheralCallback, is as follows.

Table 2  Introduction to the operation callback API of Bluetooth low energy peripheral devices

interface name

Functional description

servicesDiscoveredEvent(int status)

Callback triggered by a peripheral service update.

connectionStateChangeEvent(int connectionState)

Callback when the state of the peripheral's GATT connection changes.

characteristicReadEvent(GattCharacteristic characteristic, int ret)

GATT characteristic value read operation callback.

characteristicWriteEvent(GattCharacteristic characteristic, int ret)

GATT characteristic value write operation callback.

characteristicChangedEvent(GattCharacteristic characteristic)

Callback triggered by peripheral feature notifications.

descriptorReadEvent(GattDescriptor descriptor, int ret)

GATT description value read operation callback.

descriptorWriteEvent(GattDescriptor descriptor, int ret)

GATT description value write operation callback.

readRemoteRssiEvent(int rssi, int ret)

The callback sent by the peripheral to read the RSSI.

mtuUpdateEvent(int mtu, int ret)

Callback for MTU change notification for GATT device link.

development steps

  1. Call the startScan() interface to start BLE scanning to obtain peripheral devices.
  2. 获取到外围设备后,调用connect(boolean isAutoConnect, BlePeripheraCallback callback)建立与外围BLE设备的GATT连接,boolean参数isAutoConnect用于设置是否允许设备在可发现距离内自动建立GATT连接。
  3. 启动GATT连接后,会触发connectionStateChangeEvent(int connectionState)回调,根据回调结果判断是否连接GATT成功。
  4. 在GATT连接成功时,中心设备可以调用discoverServices()接口,获取外围设备支持的Services、Characteristics等特征值,在回调servicesDiscoveredEvent(int status)中获取外围设备支持的服务和特征值,并根据UUID判断是什么服务。
  5. 根据获取到的服务和特征值,调用read和write方法可以读取或者写入对应特征值数据。
private List<GattService> services;
// 创建扫描过滤器然后开始扫描
List<BleScanFilter> filters = new ArrayList<BleScanFilter>();
centralManager.startScan(filters);
// 与外围设备建立连接,允许自动回连,连接会触发connectionStateChangeEvent回调
private BlePeripheralDevice peripheralDevice = BlePeripheralDevice.createInstance(address); // address为远端设备地址
MyBlePeripheralCallback callback = new MyBlePeripheralCallback();
peripheralDevice.connect(true, callback);
// 连接后读取外围设备RSSI值,获取后触发readRemoteRssiEvent()回调
peripheralDevice.readRemoteRssiValue();

// 实现外围设备操作回调
private class MyBlePeripheralCallback extends BlePeripheralCallback {
    @Override
    public void connectionStateChangeEvent(int connectionState) { // GATT连接状态变化回调
        if (connectionState == ProfileBase.STATE_CONNECTED){
            peripheralDevice.discoverServices(); // 连接成功获取外围设备的Service
        } 
    }

    @Override
    public void servicesDiscoveredEvent(int status) { // 获取外围设备Service的回调
        if (status == BlePeripheralDevice.OPERATION_SUCC){
            services = peripheralDevice.getServices(); // 获取Service成功后获服务列表
            for (GattService service : services){
                // 对每个服务进行相应操作
            }
        }
    }

    @Override
    public void characteristicChangedEvent(GattCharacteristic charecteristic) { // 外围设备主动向中心设备发送特征值通知时触发回调
        // 根据通知的charecteristic获取特征值携带的数据
    }

    @Override
    public void characteristicWriteEvent(GattCharacteristic charecteristic, int ret) {
        if (ret == BlePeripheralDevice.OPERATION_SUCC){
            // 向外围设备写特征值数据成功后的操作
        }
    }

    @Override
    public void characteristicReadEvent(GattCharacteristic charecteristic, int ret) {
        if (ret == BlePeripheralDevice.OPERATION_SUCC){
            // 向外围设备读特征值数据成功后的操作
        }
    }

    @Override
    public void descriptorReadEvent(GattDescriptor descriptor, int ret) {
            // 向外围设备读描述值数据成功后的操作
    }

    @Override
    public void descriptorWriteEvent(GattDescriptor descriptor, int ret) {
           // 向外围设备写描述值数据成功后的操作
    }

    @Override
    public void readRemoteRssiEvent(int rssi, int ret) {   
        if (ret == BlePeripheralDevice.OPERATION_SUCC){
            // 读取外围设备RSSI值成功后的操作,对端RSSI值为rssi
        }
    }
}

BLE外围设备数据管理

场景介绍

BLE外围设备作为服务端,可以接收来自中心设备(客户端)的GATT连接请求,应答来自中心设备的特征值内容读取和写入请求,并向中心设备提供数据,从而实现信息交互和消息同步。同时外围设备还可以主动向中心设备发送数据。

接口说明

低功耗蓝牙外围设备操作类BlePeripheralManager的接口说明如下。

表1 外围设备管理API介绍

接口名

功能描述

BlePeripheralManager(Context context, BlePeripheralManagerCallback callback, int transport)

获取外围设备管理回调对象。

getServices()

获取外围设备的所有服务。

addService(GattService service)

将GATT服务加入服务端。

cancelConnection(BlePeripheralDevice device)

取消与中心设备的GATT连接。

clearServices()

删除所有的GATT服务。

close()

关闭GATT服务端。

getDevicesByStates(int[] states)

通过状态获取连接的中心设备列表。

notifyCharacteristicChanged(BlePeripheralDevice device, GattCharacteristic characteristic, boolean confirm)

通知中心设备特征值出现变化。

removeGattService(GattService service)

移除特定的服务。

sendResponse(BlePeripheralDevice device, int requestId, int status, int offset, byte[] value)

发送回复给中心设备。

低功耗蓝牙外围设备管理回调类BlePeripheralManagerCallback的接口说明如下。

表2 外围设备管理回调API介绍

接口名

功能描述

receiveCharacteristicReadEvent(BlePeripheralDevice device, int requestId, int offset, GattCharacteristic characteristic)

收到中心设备对特征值的读取请求回调。

receiveCharacteristicWriteEvent(BlePeripheralDevice device, int requestId, GattCharacteristic characteristic, boolean isPrep, boolean needRsp, int offset, byte[] value)

收到中心设备对特征值的写入请求。

connectionStateChangeEvent(BlePeripheralDevice device, int interval, int latency, int timeout, int status)

中心设备连接事件回调。

receiveDescriptorReadEvent(BlePeripheralDevice device, int transId, int offset, GattDescriptor descriptor)

收到中心设备对描述值的读取请求回调。

receiveDescriptorWriteRequestEvent(BlePeripheralDevice device, int transId, GattDescriptor descriptor, boolean isPrep, boolean needRsp, int offset, byte[] value)

收到中心设备对描述值的写入请求回调。

executeWriteEvent(BlePeripheralDevice device, int requestId, boolean execute)

向中心设备执行写入操作的回调。

mtuUpdateEvent(BlePeripheralDevice device, int mtu)

中心设备MTU值变化的回调。

notificationSentEvent(BlePeripheralDevice device, int status)

向中心设备发送通知的回调。

serviceAddedEvent(int status, GattService service)

向外围设备添加服务结果回调。

开发步骤

  1. 调用BlePeripheralManager(Context context, BlePeripheralManagerCallback callback, int transport)接口创建外围设备服务端并开启服务。
  2. 调用GattService(UUID uuid, boolean isPrimary)接口创建服务对象,向外围设备添加服务。
  3. 从回调接口onCharacteristicWriteRequest中获取中心设备发送来的消息,调用notifyCharacteristicChanged接口向中心设备发送通知。
private BlePeripheralDevice blePeripheralDevice;
private MyBlePeripheralManagerCallback peripheralManagerCallback = new MyBlePeripheralManagerCallback();
// 创建外围设备服务端并开启服务
private BlePeripheralManager peripheralManager = new BlePeripheralManager(this, peripheralManagerCallback, 0);
// 创建服务对象,向外围设备添加服务
private GattService service = new GattService(UUID.fromString(Service_UUID), true);
private GattCharacteristic writeCharacteristic = new GattCharacteristic(Character_UUID, 
GattCharacteristic.PROPERTY_WRITE, GattCharacteristic.PROPERTY_WRITE);
service.addCharacteristic(writeCharacteristic);
peripheralManager.addServerService(service);
// 向中心设备发送通知
writeCharacteristic.setValue(data);
peripheralManager.notifyCharacteristicChanged(blePeripheralDevice, writeCharacteristic, false);

// 外围设备管理回调
public class MyBlePeripheralManagerCallback extends BlePeripheralManagerCallback {
    // 中心设备向外围设备写入数据回调
    @Override
    public void receiveCharacteristicWriteEvent(BlePeripheralDevice device, int requestId, 
        GattCharacteristic characteristic, boolean isPrep, boolean needRsp, int offset, byte[] value){ 
            // 中心设备写入外围设备的数据为value,对数据进行处理
    }
    // 外围设备连接状态变化回调
    @Override
    public void connectionStateChangeEvent(BlePeripheralDevice device, int interval, int latency, int timeout, int status){
        if (status == ProfileBase.STATE_CONNECTED) {
            // 中心设备连接服务端成功
            blePeripheralDevice = device;
        }
    }
    // 向中心设备发送通知回调
    @Override
    public void notificationSentEvent(BlePeripheralDevice device, int status){
        if (status == BlePeripheralDevice.OPERATION_SUCC) {
            // 向对中心设备发送通知成功回调
        }
    }
}

Guess you like

Origin blog.csdn.net/weixin_47094733/article/details/131469226