1# DSoftBus 2 3## Introduction 4 5There are various ways of communication (such as Wi-Fi and Bluetooth) between devices. The difference in the usage of these communication methods may lead to communication issues. In addition, there are many challenges in converging and sharing communication links between devices and handling conflicts. 6 7DSoftBus implements unified distributed communications between near-field devices and provides APIs for device discovery, connections, networking, and data transmission, regardless of the link type. It stands out with the following capabilities: 8 9- Implements discovery and connections of devices in various communication modes, such as WLAN and Bluetooth. 10- Performs unified device networking and topology management, and provides device information for data transmission. 11- Sets up channels for transmitting messages, bytes, streams, and files. 12 13You can use the APIs provided by DSoftBus to implement fast communication between devices without caring about the communication details, which accelerating deployment and running of services across platforms. 14 15## Architecture 16 17 18 19**Figure 1** DSoftBus architecture 20 21## Directory Structure 22 23The DSoftBus directory structure is as follows: 24 25```text 26//foundation/communication/dsoftbus 27├── adapter # Adaptation code 28├── components # Dependent components 29├── core # Core code 30│ ├── adapter # Adaptation code 31│ ├── authentication # Code for authentication 32│ ├── bus_center # Code for networking 33│ ├── common # Common code 34│ ├── connection # Code for device connections 35│ ├── discovery # Code for device discovery 36│ ├── frame # Framework code 37│ └── transmission # Code for data transmission 38├── interfaces # External APIs 39├── sdk # SDK 40│ ├── bus_center # Networking 41│ ├── discovery # Device discovery 42│ ├── frame # Framework 43│ └── transmission # Transmission 44├── tests # Test code 45└── tools # Tools 46``` 47 48## Constraints 49 50- Connections can be set up only between the devices in the same LAN or between near-field devices. 51- Before setting up a connection between two devices, you must bind devices. For details, see [Security](https://gitee.com/openharmony/docs/blob/master/en/readme/Security.md). 52- After data transmission is complete, the service needs to close the session to release resources. 53 54## Usage 55 56>**NOTE** 57> 58>The permissions ohos.permission.DISTRIBUTED_DATASYNC and ohos.permission.DISTRIBUTED_SOFTBUS_CENTER are required for remote procedure calls (RPCs) across devices. 59 60### Device Discovery 61 62- **Publishing process** 63 641. Call **PublishLNN()** to publish application information across a network. 65 66 ```C 67 // Callback used to return the publish result. 68 typedef struct { 69 /** Callback for publish result */ 70 void (*OnPublishResult)(int publishId, PublishResult reason); 71 } IPublishCb; 72 73 // Information to publish. 74 typedef struct { 75 int publishId; // Publish ID. 76 DiscoverMode mode; // Discovery mode. 77 ExchangeMedium medium; // Medium to use. 78 ExchangeFreq freq; // Frequency to use. 79 const char *capability; // Capability of the device to discover. 80 unsigned char *capabilityData; // Custom data to publish. 81 unsigned int dataLen; // Data length. 82 bool ranging; // Whether ranging is required. 83 } PublishInfo; 84 85 // Publish information. 86 int32_t PublishLNN(const char *pkgName, const PublishInfo *info, const IPublishCb *cb); 87 ``` 88 892. Call **StopPublishLNN** to stop publishing information when it is not required. 90 91 ```C 92 // Stop publishing a service. 93 int32_t StopPublishLNN(const char *pkgName, int32_t publishId); 94 ``` 95 96 97- **Discovery process** 98 991. Call **RefreshLNN()** to discover devices with the specified capability. 100 101 ```C 102 // Callbacks for device discovery. 103 typedef struct { 104 /** Callback to be invoked when a device is found. */ 105 void (*OnDeviceFound)(const DeviceInfo *device); 106 /** Callback for a subscription result. */ 107 void (*OnDiscoverResult)(int32_t refreshId, RefreshResult reason); 108 } IRefreshCallback; 109 110 // Start device discovery. 111 int32_t RefreshLNN(const char *pkgName, const SubscribeInfo *info, const IRefreshCallback *cb); 112 ``` 113 114 DSoftBus notifies the service of the device information via a callback once a device is found. 115 1163. Call **StopRefreshLNN()** to stop device discovery. 117 118 ```C 119 // Stop the discovery. 120 int32_t StopRefreshLNN(const char *pkgName, int32_t refreshId); 121 ``` 122 123### Networking 124 1251. Initiate a request for connection with the target device address and a callback used to return the connection result. 126 127 ```C 128 // Address of the target device to connect to. 129 typedef struct { 130 ConnectionAddrType type; 131 union { 132 struct BrAddr { 133 char brMac[BT_MAC_LEN]; 134 } br; 135 struct BleAddr { 136 char bleMac[BT_MAC_LEN]; 137 uint8_t udidHash[UDID_HASH_LEN]; 138 } ble; 139 struct IpAddr { 140 char ip[IP_STR_MAX_LEN]; 141 uint16_t port; 142 } ip; 143 } info; 144 char peerUid[MAX_ACCOUNT_HASH_LEN]; 145 } ConnectionAddr; 146 147 // Address type. 148 typedef enum { 149 CONNECTION_ADDR_WLAN = 0, 150 CONNECTION_ADDR_BR, 151 CONNECTION_ADDR_BLE, 152 CONNECTION_ADDR_ETH, 153 CONNECTION_ADDR_MAX 154 } ConnectionAddrType; 155 156 // Callback used to return the connection result. 157 typedef void (*OnJoinLNNResult)(ConnectionAddr *addr, const char *networkId, int32_t retCode); 158 159 // Initiate a connection request. 160 int32_t JoinLNN(const char *pkgName, ConnectionAddr *target, OnJoinLNNResult cb); 161 ``` 162 1632. Wait for the connection result. 164 165 If **JoinLNN()** returns success, DSoftBus accepts the connection request and notifies the service of the connection result through the callback. The **addr** parameter in the callback matches the **target** parameter in **JoinLNN()**. If **retCode** in the callback is **0**, the connection is successful. In this case, the value of **networkId** is valid and will be used in the data transmission and disconnection APIs. If the value of **retCode** is not **0**, the connection fails, and the value of **networkId** is invalid. 166 1673. Transmit data using the related APIs. 168 1694. Initiate a disconnection request with the **networkId** and a callback for returing the result. 170 171 ```C 172 // Callback used to return the disconnection result. 173 typedef void (*OnLeaveLNNResult)(const char *networkId, int32_t retCode); 174 175 // Initiate a disconnection request. 176 int32_t LeaveLNN(const char *pkgName, const char *networkId, OnLeaveLNNResult cb); 177 ``` 178 1795. Wait until the disconnection is complete. 180 181 The **networkId** parameter in **OnLeaveLNNResult()** matches **networkId** in **LeaveLNN()**. If **retCode** in the callback is **0**, the disconnection is successful; otherwise, the disconnection fails. If the disconnection is successful, **networkId** becomes invalid and can no longer be used. 182 1836. Register and unregister callbacks for device state changes. 184 185 ```C 186 // Device state events. 187 #define EVENT_NODE_STATE_ONLINE 0x1 188 #define EVENT_NODE_STATE_OFFLINE 0x02 189 #define EVENT_NODE_STATE_INFO_CHANGED 0x04 190 #define EVENT_NODE_STATUS_CHANGED 0x08 191 #define EVENT_NODE_STATE_MASK 0xF 192 193 // Device information. 194 typedef struct { 195 char networkId[NETWORK_ID_BUF_LEN]; 196 char deviceName[DEVICE_NAME_BUF_LEN]; 197 uint16_t deviceTypeId; 198 } NodeBasicInfo; 199 200 // Device state event callbacks. 201 typedef struct { 202 uint32_t events; // Networking event mask. 203 void (*onNodeOnline)(NodeBasicInfo *info); // Called when the device gets online. 204 void (*onNodeOffline)(NodeBasicInfo *info); // Called when the device gets offline. 205 void (*onNodeBasicInfoChanged)(NodeBasicInfoType type, NodeBasicInfo *info); // Called when the device information changes. 206 void (*onNodeStatusChanged)(NodeStatusType type, NodeStatus *status); // Called when the device running status changes. 207 } INodeStateCb; 208 209 // Register a callback for device state events. 210 int32_t RegNodeDeviceStateCb(const char *pkgName, INodeStateCb *callback); 211 212 // Unregister a callback for device state events. 213 int32_t UnregNodeDeviceStateCb(INodeStateCb *callback); 214 ``` 215 216### Transmission 217 2181. Create a **Socket** instance. 219 220 ```C 221 typedef struct { 222 char *name; // Local socket name. 223 char *peerName; // Peer socket name. 224 char *peerNetworkId; // Peer network ID. 225 char *pkgName; // Bundle name of the caller. 226 TransDataType dataType; // Type of the data to be transmitted. 227 } SocketInfo; 228 229 // Create sockets. 230 int32_t Socket(SocketInfo info); 231 ``` 232 2332. Start listening for the socket on the server, and bind the socket on the client. 234 235 ```C 236 // Socket callbacks. 237 typedef struct { 238 void (*OnBind)(int32_t socket, PeerSocketInfo info); 239 void (*OnShutdown)(int32_t socket, ShutdownReason reason); 240 void (*OnBytes)(int32_t socket, const void *data, uint32_t dataLen); 241 void (*OnMessage)(int32_t socket, const void *data, uint32_t dataLen); 242 void (*OnStream)(int32_t socket, const StreamData *data, const StreamData *ext, const StreamFrameInfo *param); 243 void (*OnFile)(int32_t socket, FileEvent *event); 244 void (*OnQos)(int32_t socket, QoSEvent eventId, const QosTV *qos, uint32_t qosCount); 245 void (*OnError)(int32_t socket, int32_t errCode); 246 void (*OnBytesSent)(int32_t socket, uint32_t dataSeq, int32_t errCode); 247 } ISocketListener; 248 249 typedef enum { 250 QOS_TYPE_MIN_BW, // Minimum bandwidth. 251 QOS_TYPE_MAX_WAIT_TIMEOUT, // Bind timeout. 252 QOS_TYPE_MIN_LATENCY, // Minimum connection latency. 253 QOS_TYPE_RTT_LEVEL, // Round-trip time (RTT) level. 254 QOS_TYPE_MAX_BUFFER, // Maximum buffer (reserved). 255 QOS_TYPE_FIRST_PACKAGE, // Size of the first packet (reserved). 256 QOS_TYPE_MAX_IDLE_TIMEOUT, // Maximum idle time. 257 QOS_TYPE_TRANS_RELIABILITY, // Transmission reliability (reserved). 258 QOS_TYPE_BUTT, 259 } QosType; 260 261 typedef struct { 262 QosType qos; 263 int32_t value; 264 } QosTV; 265 266 // Start listening for the socket on the server. 267 int32_t Listen(int32_t socket, const QosTV qos[], uint32_t qosCount, const ISocketListener *listener); 268 269 // Bind the socket on the client. 270 int32_t Bind(int32_t socket, const QosTV qos[], uint32_t qosCount, const ISocketListener *listener); 271 ``` 272 2734. Send data to the peer device through the socket. 274 275 ```C 276 // Send bytes. 277 int32_t SendBytes(int32_t socket, const void *data, uint32_t len); 278 // Async Send bytes. dataSeq Indicates the unique seq number of the packet to be send. which cannot be zero. 279 int32_t SendBytesAsync(int32_t socket, uint32_t dataSeq, const void *data, uint32_t len); 280 // Send messages. 281 int32_t SendMessage(int32_t socket, const void *data, uint32_t len); 282 // Send a stream. 283 int32_t SendStream(int32_t socket, const StreamData *data, const StreamData *ext, const StreamFrameInfo *param); 284 // Send a file. 285 int32_t SendFile(int32_t socket, const char *sFileList[], const char *dFileList[], uint32_t fileCnt); 286 ``` 287 2884. Shut down a socket. 289 290 ```C 291 // Shut down a socket. 292 void Shutdown(int32_t socket); 293 ``` 294 295### Device Management 296 297 298- Select Wi-Fi keepalive mode. 299 300Call **ShiftLNNGear** on the DSoftBus client to invoke the server **ShiftLNNGear** through an IPC interface. The policy management module adjusts the **keepalive** property of the TCP persistent connection based on the specified policy. 301 302```C 303typedef struct { 304 ModeCycle cycle; // Keepalive probe interval. 305 ModeDuration duration; // Heartbeat mode duration. 306 bool wakeupFlag; // Whether the heartbeat signal wakes up the peer device. 307 ModeAction action; // Action to be taken during the keepalive process. 308} GearMode; 309 310typedef enum { 311 HIGH_FREQ_CYCLE = 30, // Heartbeat interval 30s. 312 MID_FREQ_CYCLE = 60, // Heartbeat interval 60s. 313 LOW_FREQ_CYCLE = 5 * 60, // Heartbeat interval 5 minutes. 314 DEFAULT_FREQ_CYCLE = 10 * 60, // Heartbeat interval 10 minutes. 315} ModeCycle; 316 317// Adjust the keepalive parameters of a TCP persistent connection based on the specified gear mode. 318int32_t ShiftLNNGear(const char *pkgName, const char *callerId, const char *targetNetworkId, const GearMode *mode); 319``` 320 321The TCP keepalive duration varies, depending on **ModeCycle**. 322 323```C 324HIGH_FREQ_CYCLE = 30, // The TCP keepalive duration is within 40s. 325MID_FREQ_CYCLE = 60, // The TCP keepalive duration is within 70s. 326LOW_FREQ_CYCLE = 5 x 60, // The TCP keepalive duration is within 315s. 327DEFAULT_FREQ_CYCLE = 10 x 60, // The TCP keepalive duration is within 615s. 328``` 329 330## Repositories Involved 331 332[DSoftBus](https://gitee.com/openharmony/docs/blob/master/en/readme/dsoftbus.md) 333 334**communication_dsoftbus** 335 336[communication_bluetooth](https://gitee.com/openharmony/communication_bluetooth) 337 338[communication_ipc](https://gitee.com/openharmony/communication_ipc) 339 340[communication_wifi](https://gitee.com/openharmony/communication_wifi) 341