1# BLE Development 2 3## Introduction 4Bluetooth advertising and scanning help discover Bluetooth-enabled devices and implement BLE communication. This topic walks you through on how to start and stop Bluetooth advertising and scanning. 5 6## When to Use 7You can use the APIs provided by the **ble** module to: 8 9- Start and stop BLE advertising. 10- Start and stop BLE scanning. 11 12## Available APIs 13 14For details about the APIs and sample code, see [@ohos.bluetooth.ble](../../reference/apis-connectivity-kit/js-apis-bluetooth-ble.md). 15 16The following table describes the related APIs. 17 18| API | Description | 19| ---------------------------------- | ------------------------------------------------------------------------------ | 20| startBLEScan() | Starts BLE scanning. | 21| stopBLEScan() | Stops BLE scanning. | 22| startAdvertising() | Starts BLE advertising. | 23| disableAdvertising() | Disables BLE advertising temporarily. | 24| enableAdvertising() | Enables BLE advertising temporarily. | 25| stopAdvertising() | Stops BLE advertising. | 26| on(type: 'advertisingStateChange') | Subscribes to BLE advertising state changes. | 27| off(type: 'advertisingStateChange')| Unsubscribes from BLE advertising state changes. | 28| on(type: 'BLEDeviceFind') | Subscribes to the BLE device discovery event. | 29| off(type: 'BLEDeviceFind') | Unsubscribes from the BLE device discovery event. | 30 31## How to Develop 32 33### Starting and Stopping BLE Advertising 341. Import the **ble** module. 352. Enable Bluetooth on the device. 363. Check that the SystemCapability.Communication.Bluetooth.Core capability is available. 374. Start BLE advertising. The peer device scans the advertisement. 385. Stop BLE advertising. 39Example: 40 41 ```ts 42 import { ble } from '@kit.ConnectivityKit'; 43 import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 44 45 const TAG: string = 'BleAdvertisingManager'; 46 47 export class BleAdvertisingManager { 48 private advHandle: number = 0xFF; // default invalid value 49 50 // 1. Subscribe to BLE advertising state changes. 51 public onAdvertisingStateChange() { 52 try { 53 ble.on('advertisingStateChange', (data: ble.AdvertisingStateChangeInfo) => { 54 console.info(TAG, 'bluetooth advertising state = ' + JSON.stringify(data)); 55 AppStorage.setOrCreate('advertiserState', data.state); 56 }); 57 } catch (err) { 58 console.error(TAG, 'errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 59 } 60 } 61 62 // 2. Start BLE advertising the first time. 63 public async startAdvertising() { 64 // 2.1 Set BLE advertising parameters. 65 let setting: ble.AdvertiseSetting = { 66 interval: 160, 67 txPower: 0, 68 connectable: true 69 }; 70 // 2.2 Construct the data to be advertised. 71 let manufactureValueBuffer = new Uint8Array(4); 72 manufactureValueBuffer[0] = 1; 73 manufactureValueBuffer[1] = 2; 74 manufactureValueBuffer[2] = 3; 75 manufactureValueBuffer[3] = 4; 76 let serviceValueBuffer = new Uint8Array(4); 77 serviceValueBuffer[0] = 5; 78 serviceValueBuffer[1] = 6; 79 serviceValueBuffer[2] = 7; 80 serviceValueBuffer[3] = 8; 81 let manufactureDataUnit: ble.ManufactureData = { 82 manufactureId: 4567, 83 manufactureValue: manufactureValueBuffer.buffer 84 }; 85 let serviceDataUnit: ble.ServiceData = { 86 serviceUuid: "00001888-0000-1000-8000-00805f9b34fb", 87 serviceValue: serviceValueBuffer.buffer 88 }; 89 let advData: ble.AdvertiseData = { 90 serviceUuids: ["00001888-0000-1000-8000-00805f9b34fb"], 91 manufactureData: [manufactureDataUnit], 92 serviceData: [serviceDataUnit], 93 includeDeviceName: false // Whether the device name is carried. This parameter is optional. Note that the length of an advertising packet including the device name cannot exceed 31 bytes. 94 }; 95 let advResponse: ble.AdvertiseData = { 96 serviceUuids: ["00001888-0000-1000-8000-00805f9b34fb"], 97 manufactureData: [manufactureDataUnit], 98 serviceData: [serviceDataUnit] 99 }; 100 // 2.3 Construct AdvertisingParams for starting the BLE advertising. 101 let advertisingParams: ble.AdvertisingParams = { 102 advertisingSettings: setting, 103 advertisingData: advData, 104 advertisingResponse: advResponse, 105 duration: 0 // This parameter is optional. If the value is greater than 0, the advertising stops temporarily after a period of time. You can restart it as required. 106 } 107 108 // 2.4 Start BLE advertising the first time. The ID of the BLE advertising is returned. 109 try { 110 this.onAdvertisingStateChange(); 111 this.advHandle = await ble.startAdvertising(advertisingParams); 112 } catch (err) { 113 console.error(TAG, 'errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 114 } 115 } 116 117 // 4. Disable the BLE advertising temporarily. The advertising resources still exist. 118 public async disableAdvertising() { 119 // 4.1 Construct parameters for temporarily disabling the BLE advertising. 120 let advertisingDisableParams: ble.AdvertisingDisableParams = { 121 advertisingId: this.advHandle // Use the ID of the first BLE advertising. 122 } 123 // 4.2 Disable the BLE advertising temporarily. 124 try { 125 await ble.disableAdvertising(advertisingDisableParams); 126 } catch (err) { 127 console.error(TAG, 'errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 128 } 129 } 130 131 // 5. Enable the BLE advertising again. 132 public async enableAdvertising(enableDuration: number) { 133 // 5.1 Construct the parameters for temporarily enabling the advertising. 134 let advertisingEnableParams: ble.AdvertisingEnableParams = { 135 advertisingId: this.advHandle // Use the ID of the first BLE advertising. 136 duration: enableDuration 137 } 138 // 5.2 Enable BLE advertising again. 139 try { 140 await ble.enableAdvertising(advertisingEnableParams); 141 } catch (err) { 142 console.error(TAG, 'errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 143 } 144 } 145 146 // 6. Stop BLE advertising and release related resources. 147 public async stopAdvertising() { 148 try { 149 await ble.stopAdvertising(this.advHandle); 150 ble.off('advertisingStateChange', (data: ble.AdvertisingStateChangeInfo) => { 151 console.info(TAG, 'bluetooth advertising state = ' + JSON.stringify(data)); 152 }); 153 } catch (err) { 154 console.error(TAG, 'errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 155 } 156 } 157 } 158 159 let bleAdvertisingManager = new BleAdvertisingManager(); 160 export default bleAdvertisingManager as BleAdvertisingManager; 161 ``` 162 163For details about the error codes, see [Bluetooth Error Codes](../../reference/apis-connectivity-kit/errorcode-bluetoothManager.md). 164 165### Starting and Stop BLE Scanning 1661. Import the **ble** module. 1672. Enable Bluetooth on the device. 1683. Check that the SystemCapability.Communication.Bluetooth.Core capability is available. 1694. Start BLE advertising on the peer device. 1705. Start BLE scanning on the local device. 1716. Stop BLE scanning. 172Example: 173 174 ```ts 175 import { ble } from '@kit.ConnectivityKit'; 176 import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 177 178 const TAG: string = 'BleScanManager'; 179 180 export class BleScanManager { 181 // 1. Subscribe to the scanning result. 182 public onScanResult() { 183 ble.on('BLEDeviceFind', (data: Array<ble.ScanResult>) => { 184 if (data.length > 0) { 185 console.info(TAG, 'BLE scan result = ' + data[0].deviceId); 186 } 187 }); 188 } 189 190 // 2. Start scanning. 191 public startScan() { 192 // 2.1 Construct a scan filter that matches the expected advertising packet content. 193 let manufactureId = 4567; 194 let manufactureData: Uint8Array = new Uint8Array([1, 2, 3, 4]); 195 let manufactureDataMask: Uint8Array = new Uint8Array([0xFF, 0xFF, 0xFF, 0xFF]); 196 let scanFilter: ble.ScanFilter = {// Define the filter based on site requirements. 197 manufactureId: manufactureId, 198 manufactureData: manufactureData.buffer, 199 manufactureDataMask: manufactureDataMask.buffer 200 }; 201 202 // 2.2 Construct scanning parameters. 203 let scanOptions: ble.ScanOptions = { 204 interval: 0, 205 dutyMode: ble.ScanDuty.SCAN_MODE_LOW_POWER, 206 matchMode: ble.MatchMode.MATCH_MODE_AGGRESSIVE 207 } 208 try { 209 this.onScanResult(); // Subscribe to the scanning result. 210 ble.startBLEScan([scanFilter], scanOptions); 211 console.info(TAG, 'startBleScan success'); 212 } catch (err) { 213 console.error(TAG, 'errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 214 } 215 } 216 217 // 3. Stop scanning. 218 public stopScan() { 219 try { 220 ble.off('BLEDeviceFind', (data: Array<ble.ScanResult>) => { // Unsubscribe from the scanning result. 221 console.info(TAG, 'off success'); 222 }); 223 ble.stopBLEScan(); 224 console.info(TAG, 'stopBleScan success'); 225 } catch (err) { 226 console.error(TAG, 'errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 227 } 228 } 229 } 230 231 let bleScanManager = new BleScanManager(); 232 export default bleScanManager as BleScanManager; 233 ``` 234 235For details about the error codes, see [Bluetooth Error Codes](../../reference/apis-connectivity-kit/errorcode-bluetoothManager.md).