1# Enhanced Connection Development 2<!--Kit: Distributed Service Kit--> 3<!--Subsystem: DistributedSched--> 4<!--Owner: @wangJE--> 5<!--Designer: @lee_jet520--> 6<!--Tester: @Ytt-test--> 7<!--Adviser: @w_Machine_cc--> 8## Overview 9 10With the advancement of technology, a myriad of new applications emerge, and the interconnection of devices has become the norm. Consequently, reliance on network connectivity has become inevitable. However, in certain scenarios such as aviation and ocean navigation, network access is constrained, making Bluetooth one of the few viable connection methods. Nevertheless, classic Bluetooth connections suffer from drawbacks like limited connection capacity, low connection success rates, and unstable connectivity, all of which undermine user experience. 11 12The **linkEnhance** module offers the enhanced connection functionality to enable cross-device connectivity, allowing devices to set up connections with each other and exchange application service data. Compared with classic Bluetooth connections, this functionality employs a multi-channel merging algorithm to increase the number of connectable devices and boost connection stability, significantly improving user experience. 13 14### Implementation Principles 15 16During device interconnection, the local device identifies the peer's Bluetooth address and establishes a physical link. In cross-device scenarios, a unique multi-channel merging algorithm is applied to reduce the number of physical links while ensuring device interaction. This effectively increases the number of available connections between devices, reduces interference, and enhances communication stability. 17 18The implementation process is as follows: 1. Enable the enhanced connection functionality on both the local and peer devices. 2. Make the local and the peer devices simultaneously initiate a connection request. 3. Identify and combine redundant physical links to reduce Bluetooth link resource consumption, increasing the number of available connections. 19 20 21 22### For details, see Notes and Constraints. 23 24- Bluetooth must be enabled for device interconnection. 25 26- The BLE MAC address of the peer device has been obtained through the Bluetooth advertising or scan API. For details about the APIs, see [BLE Development](../connectivity/bluetooth/ble-development-guide.md) 27 28- Cross-device collaboration is supported only for applications with the same bundle name on different devices. 29 30- The caller must have the **ohos.permission.DISTRIBUTED_DATASYNC** permission. 31 32- The **linkEnhance** module provides only connection capabilities, with the link security policy following the Bluetooth pairing policy initially set by the caller, such as Numeric Comparison, Passkey Entry, Just Works, and Out of Band. 33 34## Environment preparation 35 36### Environment requirement 37 38Bluetooth is enabled on the client and server devices. 39 40### Environment Setup 41 421. Install DevEco Studio 4.1 or later on the PC. 432. Update the public-SDK to API version 20 or later. 443. Connect device A and device B to the PC using USB cables. 454. Enable Bluetooth on device A and device B. 46 47## Available APIs 48 49The following table describes the commonly used APIs. For details, see [@ohos.distributedsched.linkEnhance](../reference/apis-distributedservice-kit/js-apis-link-enhance.md). 50 51| Name | Feature Description | 52| ------------------------------------------ | ------------------------------------------------------------------------------------------------------ | 53| connect() | Initiates a connection to the peer device on the client. | 54| disconnect() | Disconnects from the peer device. | 55| close() | Destroys a **Connection** object and unregisters all event callbacks. The **Connection** object cannot be used after this API is called. | 56| getPeerDeviceId() | Obtains the device ID of the peer device. | 57| sendData(data:ArrayBuffer) | Sends data to the peer device. | 58| on(type: 'connectResult') | Subscribes to connection events. | 59| on(type: 'disconnected') | Subscribes to disconnection events. | 60| on(type: 'dataReceived') | Subscribes to data receiving events. | 61| createConnection(deviceId: string,name:string)| Creates a **Connection** object. | 62| start() | Starts the server. | 63| stop() | Stops the server. | 64| close() | Destroys a **Server** object and cancels all subscribed event callbacks. The **Server** object cannot be used after this API is called. | 65| on(type: 'acceptConnected') | Subscribes to **acceptConnected** events. | 66| on(type: 'serverStopped') | Subscribes to **serverStopped** events. | 67| createServer(name: string) | Creates a **Server** object. | 68 69## Enhanced Connection Development 70 71- After Bluetooth is enabled on the server, create a **Server** object and call **start()** to start the server so that it is in the connectable state. Then, listen for status change events through the registered event listener. 72- After Bluetooth is enabled on the client, create a **Connection** object and call **connect()** to initiate a connection. Then, listen for status change events through the registered event listener. 73- After the connection is successful, call **sendData** to send data. 74 75### Server Development 761. Import the required module. 77 ```ts 78 import {linkEnhance} from '@kit.DistributedServiceKit'; 79 import { BusinessError } from '@kit.BasicServicesKit'; 80 ``` 812. Declare the **ohos.permission.DISTRIBUTED_DATASYNC** permission in the **module.json5** file. 82 83 ```ts 84 { 85 "module" : { 86 "requestPermissions":[ 87 { 88 "name" : "ohos.permission.DISTRIBUTED_DATASYNC", 89 "reason": "$string:distributed_permission", 90 "usedScene": { 91 "abilities": [ 92 "MainAbility" 93 ], 94 "when": "inuse" 95 } 96 } 97 ] 98 } 99 } 100 ``` 1013. Create a **Server** object, start the server, and register an event listener. 102 ```ts 103 const TAG = 'TEST'; 104 // Register the server. 105 linkEnhanceStart(name: string) { 106 console.info(TAG + 'start server deviceId = ' + name); 107 try { 108 // Construct a Server object using the specified name. 109 let server: linkEnhance.Server = linkEnhance.createServer(name); 110 111 // Subscribe to connectionAccepted events and serverStopped events. 112 server.on('connectionAccepted', (connection: linkEnhance.Connection): void => { 113 console.info(TAG + 'serverOnCallback'); 114 }); 115 server.on('serverStopped', (reason: number): void => { 116 console.info(TAG, 'serverStopped, reason= ' + reason); 117 }); 118 // Start the server. 119 server.start(); 120 } catch (err) { 121 console.error(TAG + 'start server errCode: ' + (err as BusinessError).code + ', errMessage: ' + 122 (err as BusinessError).message); 123 } 124 } 125 ``` 1265. Save the **Connection** object when the connection is established. 127 ```ts 128 serverAcceptOnCallback = (connection: linkEnhance.Connection): void => { 129 console.info(TAG + 'serverOnCallback'); 130 try { 131 132 // Subscribe to disconnection events. 133 connection.on('disconnected', (reason: number)=> { 134 console.info(TAG + 'disconnected, reason = ' + reason); 135 }); 136 // Subscribe to data receiving events. 137 connection.on('dataReceived', (data: ArrayBuffer)=> { 138 console.info(TAG + 'dataReceived, dataLen=' + data.byteLength); 139 }); 140 141 let len = 1; 142 let arraybuffer = new ArrayBuffer(len); 143 // Send data to the peer end. 144 connection.sendData(arraybuffer); 145 } catch (err) { 146 console.error(TAG + 'server on callback errCode: ' + (err as BusinessError).code + ', errMessage: ' + 147 (err as BusinessError).message); 148 } 149 } 150 ``` 1516. Disconnect from the peer end and destroy the **Connection** object. 152 ```ts 153 // Disconnect from the peer end. 154 linkEnhanceDisconnect(connection: linkEnhance.Connection) { 155 console.info(TAG + 'disconnect deviceId = ' + connection.getPeerDeviceId()); 156 try { 157 connection.disconnect(); 158 connection.close(); 159 } catch (err) { 160 console.error(TAG + 'disconnect errCode: ' + (err as BusinessError).code + ', errMessage: ' + 161 (err as BusinessError).message); 162 } 163 } 164 ``` 1657. Stop the server and destroy the **Server** object. 166 ```ts 167 // Stop the server. 168 linkEnhanceStop(server: linkEnhance.Server) { 169 console.info(TAG + 'stop server'); 170 try { 171 server.stop(); 172 } catch (err) { 173 console.info(TAG + 'stop server errCode: ' + (err as BusinessError).code + ', errMessage: ' + 174 (err as BusinessError).message); 175 } 176 } 177 // Stop the server and cancel all subscribed event callbacks. 178 linkEnhanceClose(server: linkEnhance.Server) { 179 console.info(TAG + 'close server' ); 180 try { 181 server.close(); 182 } catch (err) { 183 console.error(TAG + 'close server errCode: ' + (err as BusinessError).code + ', errMessage: ' + 184 (err as BusinessError).message); 185 } 186 } 187 ``` 188 189### Client Development 190 1911. Import the required module. 192 ```ts 193 import linkEnhance from '@kit.DistributedServiceKit'; 194 import { BusinessError } from '@kit.BasicServicesKit'; 195 ``` 1962. Declare the **ohos.permission.DISTRIBUTED_DATASYNC** permission in the **module.json5** file. 197 ```ts 198 { 199 "module" : { 200 "requestPermissions":[ 201 { 202 "name" : "ohos.permission.DISTRIBUTED_DATASYNC", 203 "reason": "$string:distributed_permission", 204 "usedScene": { 205 "abilities": [ 206 "MainAbility" 207 ], 208 "when": "inuse" 209 } 210 } 211 ] 212 } 213 } 214 ``` 2153. Create a **Connection** object, subscribe to connection events, and connect to the server. 216 ```ts 217 const TAG = "testDemo"; 218 // Connect to the server. 219 linkEnhanceConnect(peerDeviceId: string) { 220 console.info(TAG + 'connection server deviceId = ' + peerDeviceId); 221 try { 222 // Construct a Connection object by using peerDeviceId. The object is used for subsequent interactions. 223 let connection: linkEnhance.Connection = linkEnhance.createConnection(peerDeviceId, "demo"); 224 // Subscribe to connectResult events. 225 connection.on('connectResult', (data: linkEnhance.ConnectResult): void => { 226 console.info(TAG + 'clientConnectResultCallback result = ' + data.success); 227 if (data.success) { 228 // Send data to the server. 229 let len = 1; 230 let arraybuffer = new ArrayBuffer(len); 231 connection.sendData(arraybuffer); 232 } 233 }); 234 connection.on('disconnected', (reason: number)=> { 235 console.info(TAG + 'disconnected reason = ' + reason); 236 }); 237 connection.on('dataReceived', (data: ArrayBuffer)=> { 238 console.info(TAG + 'dataReceived, dataLen=' + data.byteLength); 239 }); 240 // Initiate a connection. 241 connection.connect(); 242 } catch (err) { 243 console.error(TAG + 'connect errCode: ' + (err as BusinessError).code + ', errMessage: ' + 244 (err as BusinessError).message); 245 } 246 } 247 ``` 2484. Disconnect from the server and destroy the **Connection** object. 249 ```ts 250 disconnect(connection: linkEnhance.Connection) { 251 console.info(TAG + 'disconnect deviceId = ' + connection.getPeerDeviceId()); 252 try { 253 connection.disconnect(); 254 connection.close(); 255 } catch (err) { 256 console.error(TAG + 'disconnect errCode: ' + (err as BusinessError).code + ', errMessage: ' + 257 (err as BusinessError).message); 258 } 259 } 260 ``` 261