1# DSoftBus
2
3
4## Introduction
5
6DSoftBus implements unified distributed communications between near-field devices and provides APIs for device discovery, connection, networking, and data transmission, regardless of the link type. It provides the following capabilities:
7
8-   Device discovery and connection in various communication modes, such as WLAN and Bluetooth.
9-   Unified device networking and topology management, and device information provisioning for data transmission.
10-   Channel setup for transmitting messages, bytes, streams, and files.
11
12You can use the APIs provided by DSoftBus to implement fast communication between devices without caring about the communication details, which facilitating deployment and running of services across platforms.
13
14## Architecture
15
16![](figures/dsoftbus-architecture.png)
17
18**Figure 1** DSoftBus architecture
19
20## Directory Structure
21
22The DSoftBus directory structure is as follows:
23
24```text
25//foundation/communication/dsoftbus
26├── adapter               # Adaptation code
27├── components            # Dependent component code
28├── core                  # Core code
29│   ├── adapter           # Adaptation code
30│   ├── authentication    # Authentication code
31│   ├── bus_center        # Networking code
32│   ├── common            # Common code
33│   ├── connection        # Connection code
34│   ├── discovery         # Discovery code
35│   ├── frame             # Framework code
36│   └── transmission      # Transmission code
37├── interfaces            # External APIs
38├── sdk                   # Service process code
39│   ├── bus_center        # Networking code
40│   ├── discovery         # Discovery code
41│   ├── frame             # Framework code
42│   └── transmission      # Transmission code
43├── tests                 # Test code
44└── tools                 # Tool code
45```
46
47## Constraints
48
49-   Connections can be set up only between the devices in the same LAN or between near-field devices.
50-   Before setting up a connection between two devices, you must bind the devices. For details about the binding process, see [the Security subsystem](https://gitee.com/openharmony/docs/blob/master/zh-cn/readme/%E5%AE%89%E5%85%A8%E5%9F%BA%E7%A1%80%E8%83%BD%E5%8A%9B%E5%AD%90%E7%B3%BB%E7%BB%9F.md) readme file.
51-   After data transmission is complete, the service needs to close the session to release resources.
52
53## Usage
54
55### Usage Guidelines
56
57>**NOTE**
58>
59>- The permissions ohos.permission.DISTRIBUTED_DATASYNC and ohos.permission.DISTRIBUTED_SOFTBUS_CENTER are required for remote procedure calls (RPCs) across devices.
60
61**1. Discovery**
62
63-   **Publishing process**
64
651.  Publish a service of your application.
66
67    ```C
68    // Callback for service publishing.
69    typedef struct {
70        /** Callback used to return the publish result. */
71        void (*OnPublishResult)(int publishId, PublishResult reason);
72    } IPublishCb;
73
74    // Publish information.
75    typedef struct {
76        int publishId;                 // Publish ID.
77        DiscoverMode mode;             // Publish mode.
78        ExchangeMedium medium;         // Medium used for publishing the service.
79        ExchangeFreq freq;             // Service publishing frequency.
80        const char *capability;        // Capability of the device that can be discovered.
81        unsigned char *capabilityData; // Custom data for service publishing
82        unsigned int dataLen;          // Length of the data.
83        bool ranging;                  // Whether to measure the distance.
84    } PublishInfo;
85
86    // Publish a service.
87    int32_t PublishLNN(const char *pkgName, const PublishInfo *info, const IPublishCb *cb);
88    ```
89
902.  Unpublish a service of your application.
91
92    ```C
93    // Unpublish a service.
94    int32_t StopPublishLNN(const char *pkgName, int32_t publishId);
95    ```
96
97
98-   **Discovery process**
99
1001.  Discover a device.
101
102    ```C
103    // Callbacks for device discovery.
104    typedef struct {
105        /** Callback invoked when a device is found. */
106        void (*OnDeviceFound)(const DeviceInfo *device);
107        /** Callback invoked to return the device discovery result. */
108        void (*OnDiscoverResult)(int32_t refreshId, RefreshResult reason);
109    } IRefreshCallback;
110
111    // Start device discovery.
112    int32_t RefreshLNN(const char *pkgName, const SubscribeInfo *info, const IRefreshCallback *cb);
113    ```
114
1152.  DSoftBus notifies the service of the device information via the callback once a device is found.
1163.  Stop device discovery.
117
118    ```C
119    // Stop the discovery.
120    int32_t StopRefreshLNN(const char *pkgName, int32_t refreshId);
121    ```
122
123**2. Networking**
124
1251.  Initiate a connection request with the address of the target device and the connection callback.
126
127    ```C
128    // Address 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 invoked 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. If DSoftBus accepts the connection request, a callback is invoked to return the result. In the return value, if **retCode** is **0**, the connection is successful, and the **addr** parameter matches the **target** parameter in **JoinLNN()**. 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.
1643.  Transmit data using transmission APIs.
1654.  Initiate a disconnection request with the **networkId** and the callback.
166
167    ```C
168    // Callback invoked to return the disconnection result.
169    typedef void (*OnLeaveLNNResult)(const char *networkId, int32_t retCode);
170
171    // Initiate a disconnection request.
172    int32_t LeaveLNN(const char *pkgName, const char *networkId, OnLeaveLNNResult cb);
173    ```
174
1755.  Wait until the disconnection is complete. The **networkId** parameter in **OnLeaveLNNResult()** matches **networkId** in **LeaveLNN()**. If **retCode** is **0**, the disconnection is successful; otherwise, the disconnection fails. If the disconnection is successful, **networkId** becomes invalid and can no longer be used.
1766.  Register and unregister callbacks for device state changes.
177
178    ```C
179    // Device state events.
180    #define EVENT_NODE_STATE_ONLINE 0x1
181    #define EVENT_NODE_STATE_OFFLINE 0x02
182    #define EVENT_NODE_STATE_INFO_CHANGED 0x04
183    #define EVENT_NODE_STATUS_CHANGED 0x08
184    #define EVENT_NODE_STATE_MASK 0xF
185
186    // Device information.
187    typedef struct {
188        char networkId[NETWORK_ID_BUF_LEN];
189        char deviceName[DEVICE_NAME_BUF_LEN];
190        uint16_t deviceTypeId;
191    } NodeBasicInfo;
192
193    // Device state event callbacks.
194    typedef struct {
195        uint32_t events; // Networking event mask.
196        void (*onNodeOnline)(NodeBasicInfo *info);   // Called when the device gets online.
197        void (*onNodeOffline)(NodeBasicInfo *info);  // Called when the device gets offline.
198        void (*onNodeBasicInfoChanged)(NodeBasicInfoType type, NodeBasicInfo *info); // Called when the device information changes.
199        void (*onNodeStatusChanged)(NodeStatusType type, NodeStatus *status); // Called when the device running status changes.
200    } INodeStateCb;
201
202    // Register the callback for device state events.
203    int32_t RegNodeDeviceStateCb(const char *pkgName, INodeStateCb *callback);
204
205    // Unregister the callback for device state events.
206    int32_t UnregNodeDeviceStateCb(INodeStateCb *callback);
207    ```
208
209**3. Transmission**
210
2111.  Create a **Socket** instance.
212
213    ```C
214    typedef struct {
215        char *name;               // Local socket name.
216        char *peerName;           // Peer socket name.
217        char *peerNetworkId;      // Peer network ID.
218        char *pkgName;            // Bundle name of the caller.
219        TransDataType dataType;   // Type of the data to be transmitted, which must be the same as that in the sender() method.
220    } SocketInfo;
221
222    // Create sockets.
223    int32_t Socket(SocketInfo info);
224    ```
225
2262.  Start listening for the socket on the server, and bind the socket on the client.
227
228    ```C
229    // Callbacks for the socket.
230    typedef struct {
231        void (*OnBind)(int32_t socket, PeerSocketInfo info);
232        void (*OnShutdown)(int32_t socket, ShutdownReason reason);
233        void (*OnBytes)(int32_t socket, const void *data, uint32_t dataLen);
234        void (*OnMessage)(int32_t socket, const void *data, uint32_t dataLen);
235        void (*OnStream)(int32_t socket, const StreamData *data, const StreamData *ext, const StreamFrameInfo *param);
236        void (*OnFile)(int32_t socket, FileEvent *event);
237        void (*OnQos)(int32_t socket, QoSEvent eventId, const QosTV *qos, uint32_t qosCount);
238        void (*OnError)(int32_t socket, int32_t errCode);
239    } ISocketListener;
240
241    typedef enum {
242        QOS_TYPE_MIN_BW,           // Minimum bandwidth.
243        QOS_TYPE_MAX_WAIT_TIMEOUT,      // Maximum time allowed for the bind operation.
244        QOS_TYPE_MIN_LATENCY,      // Minimum latency for link setup.
245        QOS_TYPE_RTT_LEVEL, // Level of the RTT.
246        QOS_TYPE_MAX_BUFFER,       // Maximum buffer size (reserved).
247        QOS_TYPE_FIRST_PACKAGE,    // Size of the first packet (reserved).
248        QOS_TYPE_MAX_IDLE_TIMEOUT, // Maximum idle time.
249        QOS_TYPE_TRANS_RELIABILITY,// Transmission reliability (reserved).
250        QOS_TYPE_BUTT,
251    } QosType;
252
253    typedef struct {
254        QosType qos;
255        int32_t value;
256    } QosTV;
257
258    // Start listening for the socket on the server.
259    int32_t Listen(int32_t socket, const QosTV qos[], uint32_t qosCount, const ISocketListener *listener);
260
261    // Bind the socket on the client.
262    int32_t Bind(int32_t socket, const QosTV qos[], uint32_t qosCount, const ISocketListener *listener);
263    ```
264
2654. Send data to the peer device through the socket.
266
267    ```C
268    // Send bytes.
269    int32_t SendBytes(int32_t socket, const void *data, uint32_t len);
270    // Send messages.
271    int32_t SendMessage(int32_t socket, const void *data, uint32_t len);
272    // Send streams.
273    int32_t SendStream(int32_t socket, const StreamData *data, const StreamData *ext, const StreamFrameInfo *param);
274    // Send a file.
275    int32_t SendFile(int32_t socket, const char *sFileList[], const char *dFileList[], uint32_t fileCnt);
276    ```
277
2785. Shut down the socket.
279
280    ```C
281    // Shut down the socket.
282    void Shutdown(int32_t socket);
283    ```
284
285**4. Device Management**
286
287-   **Choose the Wi-Fi keepalive mode.**
288
2891. Call **ShiftLNNGear** on the DSoftBus client to invoke the server **ShiftLNNGear** through an IPC interface. The policy management module adjusts the keepalive attributes of the long-lived TCP connection based on the policy.
290
291    ```C
292    typedef struct {
293        ModeCycle cycle;        // Interval for detecting whether the Wi-Fi connection is alive.
294        ModeDuration duration;  // Heartbeat mode duration.
295        bool wakeupFlag;        // Whether to wake up the peer device.
296        ModeAction action;      // Mode to select.
297    } GearMode;
298
299    typedef enum {
300        /**< The heartbeat interval is 30 seconds. */
301        HIGH_FREQ_CYCLE = 30,
302        /**< The heartbeat interval is 60 seconds. */
303        MID_FREQ_CYCLE = 60,
304        /**< The heartbeat interval is 5 minutes. */
305        LOW_FREQ_CYCLE = 5 * 60,
306        /**< The heartbeat interval is 10 minutes. */
307        DEFAULT_FREQ_CYCLE = 10 * 60,
308    } ModeCycle;
309
310    // Adjust the keepalive parameters of the long-lived TCP connection based on the policy.
311    int32_t ShiftLNNGear(const char *pkgName, const char *callerId, const char *targetNetworkId, const GearMode *mode);
312    ```
313
3142.  Set **ModeCycle** for the service, which determines the TCP keepalive duration for the device.
315
316    ```C
317    If HIGH_FREQ_CYCLE is used, the TCP keepalive duration is within 40 seconds.
318    If MID_FREQ_CYCLE is used, the actual TCP keepalive duration is within 70 seconds.
319    If LOW_FREQ_CYCLE is used, the TCP keepalive duration is within 315 seconds.
320    If DEFAULT_FREQ_CYCLE is used, the TCP keepalive duration is within 615 seconds.
321    ```
322
323## Repositories Involved
324
325[DSoftBus](https://gitee.com/openharmony/docs/blob/master/en/readme/dsoftbus.md)
326
327**communication_dsoftbus**
328
329[communication_bluetooth](https://gitee.com/openharmony/communication_bluetooth)
330
331[communication_ipc](https://gitee.com/openharmony/communication_ipc)
332
333[communication_wifi](https://gitee.com/openharmony/communication_wifi)
334