1# Bluetooth Discovery Development 2 3<!--Kit: Connectivity Kit--> 4<!--Subsystem: Communication--> 5<!--Owner: @enjoy_sunshine--> 6<!--Designer: @chengguohong; @tangjia15--> 7<!--Tester: @wangfeng517--> 8<!--Adviser: @zhang_yixin13--> 9 10## Introduction 11This document describes how to implement the Bluetooth device discovery capabilities, such as scanning for nearby devices, setting the Bluetooth scan mode, and retrieving information about paired devices. 12 13## How to Develop 14 15### Applying for Required Permissions 16Apply for the **ohos.permission.ACCESS_BLUETOOTH** permission. For details about how to configure and apply for permissions, see [Declaring Permissions](../../security/AccessToken/declare-permissions.md) and [Requesting User Authorization](../../security/AccessToken/request-user-authorization.md). 17 18### Importing Required Modules 19Import the **connection** and **BusinessError** modules. 20```ts 21import { connection } from '@kit.ConnectivityKit'; 22import { BusinessError } from '@kit.BasicServicesKit'; 23``` 24 25### Scanning for Nearby Bluetooth Devices 26This function allows your application to scan for nearby Bluetooth devices and obtain partial information about them. This process can also be referred to as search, discovery, or find. Only nearby Bluetooth devices that are in a discoverable state can be scanned by the local Bluetooth device. 27 28**1. Subscribing to Scan Result Reporting Events**<br> 29- You are advised to use the scan result reporting mode supported since API version 18. This allows you to obtain more device information, including the device address, signal strength, name, and type. For details, see [connection.on('discoveryResult')](../../reference/apis-connectivity-kit/js-apis-bluetooth-connection.md#connectionondiscoveryresult18). 30```ts 31// Define the callback for scan result reporting events. 32function onReceiveEvent(data: Array<connection.DiscoveryResult>) { 33 console.info('bluetooth device: '+ JSON.stringify(data)); 34} 35 36try { 37 // Subscribe to scan result reporting events. 38 connection.on('discoveryResult', onReceiveEvent); 39} catch (err) { 40 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 41} 42``` 43- The scan result reporting mode in API version 17 or earlier can retrieve only the device address information. For details, see [connection.on('bluetoothDeviceFind')](../../reference/apis-connectivity-kit/js-apis-bluetooth-connection.md#connectiononbluetoothdevicefind). 44```ts 45// Define the callback for scan result reporting events. 46function onReceiveEvent(data: Array<string>) { 47 console.info('bluetooth device: '+ JSON.stringify(data)); 48} 49 50try { 51 // Subscribe to scan result reporting events. 52 connection.on('bluetoothDeviceFind', onReceiveEvent); 53} catch (err) { 54 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 55} 56``` 57 58**2. Initiating a Device Scan**<br> 59A scan process takes about 12 seconds after being initiated. The application can initiate pairing, connection, and data transmission with the discovered Bluetooth device. For details, see [Device Pairing](br-pair-device-development-guide.md) and [SPP-based Connection and Data Transmission](spp-development-guide.md). 60```ts 61try { 62 // Check whether scanning is in progress on the local device. 63 let scan = connection.isBluetoothDiscovering(); 64 if (!scan) { 65 // Start scanning for devices if a scan is not in progress. 66 connection.startBluetoothDiscovery(); 67 } 68} catch (err) { 69 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 70} 71``` 72**3. Stopping the Device Scan**<br> 73Scanning is a process that consumes a large amount of Bluetooth hardware resources. When the expected Bluetooth device is discovered, the device scanning must be stopped before a connection is initiated. 74```ts 75// Define the callback for scan result reporting events. 76function onReceiveEvent(data: Array<string>) { 77 console.info('bluetooth device: '+ JSON.stringify(data)); 78} 79 80try { 81 // Check whether scanning is in progress on the local device. 82 let scan = connection.isBluetoothDiscovering(); 83 if (scan) { 84 // Stop scanning for devices if a scan is in progress. 85 connection.stopBluetoothDiscovery(); 86 } 87 // If scanning is no longer needed, unsubscribe from scan result reporting events. 88 connection.off('bluetoothDeviceFind', onReceiveEvent); 89} catch (err) { 90 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 91} 92``` 93 94### Setting the Bluetooth Scan Mode of the Local Device 95The Bluetooth scan mode of the local device determines whether the local device can be scanned or connected by other Bluetooth devices. Typically, non-system applications do not need to concern themselves with this mode, as the system settings application will handle its configuration. 96- If the Bluetooth settings screen is in the foreground when Bluetooth has been enabled, the Bluetooth scan mode of the local device is set to [SCAN_MODE_CONNECTABLE_GENERAL_DISCOVERABLE](../../reference/apis-connectivity-kit/js-apis-bluetooth-connection.md#scanmode). In this mode, the local device can be discovered by other Bluetooth devices and can accept incoming connections 97- If the Bluetooth settings screen is in the background when Bluetooth has been enabled, the Bluetooth scan mode of the local device is set to [SCAN_MODE_CONNECTABLE](../../reference/apis-connectivity-kit/js-apis-bluetooth-connection.md#scanmode). In this mode, the local device can accept incoming connections but cannot be discovered by other Bluetooth devices. 98 99```ts 100try { 101 // Obtain the current scan mode of the local device. 102 let scanMode: connection.ScanMode = connection.getBluetoothScanMode(); 103 console.info('scanMode: ' + scanMode); 104 if (scanMode != connection.ScanMode.SCAN_MODE_CONNECTABLE_GENERAL_DISCOVERABLE) { 105 // Set the scan mode of the local device to SCAN_MODE_CONNECTABLE_GENERAL_DISCOVERABLE. 106 connection.setBluetoothScanMode(connection.ScanMode.SCAN_MODE_CONNECTABLE_GENERAL_DISCOVERABLE, 0); 107 } 108} catch (err) { 109 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 110} 111``` 112 113### Retrieving Information About Paired Devices 114To streamline device scanning, check if the device is paired before initiating a scan. You can also initiate connection and data transmission processes for paired devices. For details, see [Device Pairing](br-pair-device-development-guide.md) and [SPP-based Data Transmission](spp-development-guide.md). 115 116```ts 117try { 118 // Obtain information about the paired devices. 119 let devices = connection.getPairedDevices(); 120 console.info('pairedDevices: ' + JSON.stringify(devices)); 121 // If the device address is known, check whether the device has been paired. 122 if (devices.length > 0) { 123 let pairState = connection.getPairState(devices[0]); 124 console.info('device: '+ devices[0] + ' pairState is ' + pairState); 125 } 126} catch (err) { 127 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 128} 129``` 130 131## Sample Code 132```ts 133import { connection } from '@kit.ConnectivityKit'; 134import { BusinessError } from '@kit.BasicServicesKit'; 135 136export class DiscoveryDeviceManager { 137 // Define the callback for scan result reporting events. 138 onReceiveEvent = (data: Array<string>) => { 139 console.info('bluetooth device: '+ JSON.stringify(data)); 140 }; 141 142 public startDiscovery() { 143 try { 144 connection.on('bluetoothDeviceFind', this.onReceiveEvent); 145 } catch (err) { 146 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 147 } 148 try { 149 // Check whether scanning is in progress on the local device. 150 let scan = connection.isBluetoothDiscovering(); 151 if (!scan) { 152 // Start scanning for devices if a scan is not in progress. 153 connection.startBluetoothDiscovery(); 154 } 155 } catch (err) { 156 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 157 } 158 } 159 160 public stopDiscovery() { 161 try { 162 // Check whether scanning is in progress on the local device. 163 let scan = connection.isBluetoothDiscovering(); 164 if (scan) { 165 // Stop scanning for devices if a scan is in progress. 166 connection.stopBluetoothDiscovery(); 167 } 168 // If scanning is no longer needed, unsubscribe from scan result reporting events. 169 connection.off('bluetoothDeviceFind', this.onReceiveEvent); 170 } catch (err) { 171 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 172 } 173 } 174 175 public setScanMode() { 176 try { 177 // Obtain the current scan mode of the local device. 178 let scanMode: connection.ScanMode = connection.getBluetoothScanMode(); 179 console.info('scanMode: ' + scanMode); 180 if (scanMode != connection.ScanMode.SCAN_MODE_CONNECTABLE_GENERAL_DISCOVERABLE) { 181 // Set the scan mode of the local device to SCAN_MODE_CONNECTABLE_GENERAL_DISCOVERABLE. 182 connection.setBluetoothScanMode(connection.ScanMode.SCAN_MODE_CONNECTABLE_GENERAL_DISCOVERABLE, 0); 183 } 184 } catch (err) { 185 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 186 } 187 } 188 189 public getPairedDevices() { 190 try { 191 // Obtain information about the paired devices. 192 let devices = connection.getPairedDevices(); 193 console.info('pairedDevices: ' + JSON.stringify(devices)); 194 // If the device address is known, check whether the device has been paired. 195 if (devices.length > 0) { 196 let pairState = connection.getPairState(devices[0]); 197 console.info('device: '+ devices[0] + ' pairState is ' + pairState); 198 } 199 } catch (err) { 200 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 201 } 202 } 203} 204 205let discoveryDeviceManager = new DiscoveryDeviceManager(); 206export default discoveryDeviceManager as DiscoveryDeviceManager; 207``` 208